views:

141

answers:

6

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?

A: 
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) ) ...
sbi
Would whoever down-voted this please explain what's wrong with it?
sbi
A: 

until you want it as a value ;-)

ohho
Should be a comment (somewhere) ?
Paul R
+2  A: 

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))
Paul Stephenson
Unless you're using gcc, which allows a block to return a value when used in an expression.
Paul R
@Paul R: Fair enough, I didn't know that. What about `if (FOO(some_variable))`?
Paul Stephenson
@Paul: yes - same deal - gcc lets you do this. Probably best avoided though - use inline functions instead.
Paul R
+1  A: 

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.

Paul R
Please note evaluation order and precedence are two different things.
anon
@Paul: you mean I can write something like this "if (FOO(var)) {...}" by using your FOO macro defined above?
solotim
@solotim: in gcc yes, but not in compilers which do not have this gcc extension. It's probably best to avoid gcc-specific extensions though, and even better to use inline functions rather than macros wherever possible.
Paul R
@Paul: Thank you for the advices.
solotim
+1  A: 

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,

anon
+5  A: 

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)
Donal Fellows