Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference using {} pair or () pair when define function-like macro in C?

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?

like image 373
solotim Avatar asked Dec 29 '22 18:12

solotim


1 Answers

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)
like image 106
Donal Fellows Avatar answered Jan 31 '23 07:01

Donal Fellows