I often see instances in which using a macro is better than using a function.
Could someone explain me with an example the disadvantage of a macro compared to a function?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Macros are error-prone because they rely on textual substitution and do not perform type-checking. For example, this macro:
works fine when used with an integer:
but does very strange things when used with expressions:
Putting parentheses around arguments helps but doesn’t completely eliminate these problems.
When macros contain multiple statements, you can get in trouble with control-flow constructs:
The usual strategy for fixing this is to put the statements inside a “do { … } while (0)” loop.
If you have two structures that happen to contain a field with the same name but different semantics, the same macro might work on both, with strange results:
Finally, macros can be difficult to debug, producing weird syntax errors or runtime errors that you have to expand to understand (e.g. with gcc -E), because debuggers cannot step through macros, as in this example:
Inline functions and constants help to avoid many of these problems with macros, but aren’t always applicable. Where macros are deliberately used to specify polymorphic behavior, unintentional polymorphism may be difficult to avoid. C++ has a number of features such as templates to help create complex polymorphic constructs in a typesafe way without the use of macros; see Stroustrup’s The C++ Programming Language for details.