Answer the question
In order to leave comments, you need to log in
Why are macros still used in modern projects?
In return, it seems to me the obvious solution to inline functions. The most important plus is that the function is clearer than the macro, at least it has a backlight.
Answer the question
In order to leave comments, you need to log in
Macros are needed where necessary during the compilation of the program to generate code. Functions or even templates are not suitable for this.
For example, you want a logger that would write in which file and on which line the error occurred, you write the code
And everything is fine as long as you insert it with your hands where you need it. But now you have decided that it is ugly, and you plan to move the code into a function. However, the plan fails, because now the code writes the same file every time, and the same line - the same one in which the code is conveniently located in your function. There are two ways out:
- duplicate this code every time
- use
macros
Now you can write anywhere
LOG("this is error number " << errno);
and everything will work as planned.
Another of the useful properties of macros is to improve someone else's bad code. If you have a lot of variables, or variables whose names are almost the same as function names and you need to make this code smarter, you use macros, glue strings with ## or convert a variable to a string with #
These are quite powerful tools (even to Lisp macros they are far away) that really allow you to improve the code and / or avoid a bunch of repetitions of the same block of code.
Macros should be used very rarely. The only thing that, in my opinion, can be attributed to the pluses of macros in relation to inline functions is their biggest minus - the lack of type safety. For example, to rewrite a simple macro as a function
, you will have to use templates if you need this line to work with more than one type.
However, in the vast majority, macros not only do not help, but also greatly harm.
In general, it will be useful to read Meyers "Effective C ++" (Scott Meyers "Effective C ++"), there is about it.
"Any sufficiently complex C or Fortran program contains a newly written, unspecified, buggy, and slow implementation of half of the Lisp language." So macros are needed.
Try to "inline" this:
#define FOO_MAGIC protected: foo someMagicFunction(){...} foo Bar;
// далее - мешанина из \ template typedef typename { } <> () FOO_MAGIC_1
// и прочих радостей поддержки чужого кода
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question