Is there any difference using {} pair or () pair when define function-like macro in C?
For example:
#define FOO(x) 开发者_JAVA百科 (printf(x))
and
#define FOO(x) {printf(x)}
It seems that both are viable for preprocessing, but which is better?
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)
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 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))
精彩评论