For example:
#define FOO(x) (printf(x))
and
#define FOO(x) {printf(x)}
It seems that both are viable for preprocessing, but which is better?
For example:
#define FOO(x) (printf(x))
and
#define FOO(x) {printf(x)}
It seems that both are viable for preprocessing, but which is better?
if( wrgzl )
FOO(bar);
else
BAR(foo);
And if the macro is expected to yield an expression (#define SQRT(x) sqrt(x)
), then braces don't work at all:
if( Foo(bar) ) ...
If you will ever need FOO(x)
inside an expression, then you cannot use the {}
form. For example:
result = FOO(some_variable);
or
if (FOO(some_variable))
Parentheses ()
are used to enforce correct evaluation regardless of operator precedence, so that you hopefully won't get any nasty side effects when the macro is expanded.
Braces {}
are used to make the macro a C block statement, although the canonical way to do this is:
#define FOO(x) \
do { \
... stuff ... \
} while (0)
Note that gcc provides an extension to the C language which makes it possible to return a value from a block - the last expression evaluated will be the value returned if the block is used as part of an expression.
The purpose of using parens in a macro is to control precedence when the macro is expanded. Consider:
#define X( a, b ) a * b
if the macro is used like this
X( 1 + 2, 3 )
we would presumably like the answer to be 9, but what we get on expansion is:
1 + 2 * 3
giving us 7. To avoid this kind of thing, we should have written the macro as:
#define X( a, b ) ((a) * (b))
If precedence is not an issue, brackets either type are not absolutely required, though braces may be needed depending on the ,macros semantics - if for example you want to create a local variable,
If you're treating the macro as an expression, use the ()
form.
If you're treating it as a command (and never as an expression) then use the {}
form. Or rather, use the do{}while(0)
form as that has fewer substitution hazards when used near keywords like if
:
#define FOO(x) do { \
printf(x); \
} while(0)