I always saw examples and cases where using a macro is better than using function.
Could someone explain me with an example the disadvantage of a macro compared to a function?
I always saw examples and cases where using a macro is better than using function.
Could someone explain me with an example the disadvantage of a macro compared to a function?
Side-effects are a big one. Here's a typical case:
gets expanded to:
x
gets incremented twice in the same statement. (and undefined behavior)Writing multi-line macros are also a pain:
They require a
\
at the end of each line.Macros can't "return" anything unless you make it a single expression:
Can't do that in a macro unless you use GCC's expression statement. (EDIT: You can use a comma operator though... overlooked that... But it might still be less readable.)
Order of Operations: (courtesy of @ouah)
gets expanded to:
But
&
has lower precedence than<
. So0xFF < 42
gets evaluated first.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.
one drawback to macros is that debuggers read source code, which does not have expanded macros, so running a debugger in a macro is not necessarily useful. Needless to say, you cannot set a breakpoint inside a macro like you can with functions.
Functions do type checking. This gives you an extra layer of safety.