Reputation: 26333
With C++, when do I have to #define
a macro vs inline
? Article here elaborates on why macros are evil, why use macros anyway ?
I see one:
any other?
Also, what are common use for macros, and when, in general, do macros have privileges over other implementation choices ?
Upvotes: 0
Views: 302
Reputation: 70283
A macro (#define
) is handled by the preprocessor. It is really just a simple replace operation, with no regard to the language syntax and before the compiler even gets to look at the source. There is the problem of multiple evaluation should the macro parameter have any side effects (e.g. MACRO( x++ )
).
A function is handled by the compiler. It offers proper type checking and scope, avoids the multiple evaluation problem, and provides much more meaningful error messages if you get it wrong.
And have you ever tried to step through a "macro-inlined" function using a debugger?
That's functions... uh... 5-ish, macros zero.
Now, as for the inline
keyword... if you were good enough at this to actually beat the compiler at deciding what should be inlined and what shouldn't, you wouldn't have asked this question. And even if you had a performance issue somewhere, chances are excellent that you could do much more effective things than adding inline
somewhere.
Upvotes: 1
Reputation: 808
You can always replace precompiler macro with templates and inlines. inline itself is limited to type you specified. That type is used and no else. With templates, you can take advantage of different types and use the same algorithm with anything that will compile, with specialization for some types. Problem of macro is, it can evaluate expression more than once. Templates should never do that, as template input is evaluated only once for function.
Some things, like making "module" string using STR(module), are possible only using macros.
As for speed compared between inline and old style C macros, I do not know. I think it is very compiler specific and you can tune it using compiler flags a lot. I never played with it much and I just tend to believe recent compilers are smart enough to really inline functions that can be inlined. In fact inline keyword should not be needed for that in most cases, as compiler can inline also functions without such keyword.
Upvotes: 0
Reputation: 2301
'inline' is just a hint to the compiler, it can still refuse to inline the function in the generated code.
Since a preprocessor macro is just substitution it can be guaranteed that it will be inlined, there is no function just duplication.
That being said, macros are still evil and each case should be evaluated rather than a "general rule", but if you want to a general rule always prefer inline over a macro, or trust that the compiler is smarter than you and let it decide by itself.
Upvotes: 3