The macro will be replaced by its definition (after suitable argument replacement), so consider whether the expanded code is what you want to see there.
A common concern with conditional code is what happens if it is invoked from within another conditional block. For example:
- #define demo(arg) if (arg > 0) blink()
-
if (this < that)
-
demo(that);
-
else
-
demo(this);
- ... expands to ...
-
if (this < that)
-
if (that > 0) blink();
-
else
-
if (this > 0) blink();
Notice that the 'else' ends up being associated with if(that>0) instead of if(this<that) as you would have expected from reading the source code.
The typical idiom used to prevent this from happening is to encapsulate any multi-line macro definition as follows:
- #define demo(arg) \
-
do { \
-
if (arg > 0) blink(); \
-
} while(0)
Notice that all of the source lines of the macro definition are enclosed within a set of braces, making them act like a single instruction. This prevents the else confusion described above; it also prevents you from falling out early if the macro is invoked within a non-bracketed if statement.
Notice that there is no semi-colon after while(0). This forces the programmer to terminate the macro invocation with a semi-colon.