Is there any difference with using {} pair or () when defining function macros in C?

For instance:

#define FOO(x) (printf(x)) 

and

 #define FOO(x) {printf(x)} 

Both seem viable for pretreatment, but which is better?

+4
source share
4 answers

If you treat the macro as an expression, use the form () .

If you consider it as a command (and never as an expression), use the form {} . Rather, use the do{}while(0) form, since it has fewer substitution dangers when using close keywords, such as if :

 #define FOO(x) do { \ printf(x); \ } while(0) 
+6
source

If you need FOO(x) inside an expression, you cannot use the form {} . For instance:

 result = FOO(some_variable); 

or

 if (FOO(some_variable)) 
+2
source

Parentheses () are used to provide the correct score regardless of operator precedence, so you hopefully don't get any unpleasant side effects when expanding the macro.

The braces {} are used to make a macro an operator of a C block, although the canonical way to do this is:

 #define FOO(x) \ do { \ ... stuff ... \ } while (0) 

Note that gcc provides an extension for the C language that allows you to return a value from a block - the last expressed expression will be the value returned if the block is used as part of the expression.

+2
source

The purpose of using parsers in a macro is to control priority when expanding a macro. Consider:

 #define X( a, b ) a * b 

if the macro is used as

 X( 1 + 2, 3 ) 

we would presumably want the answer to be 9, but we get the extension:

 1 + 2 * 3 

giving us 7. To avoid this kind of thing, we had to write a macro like:

 #define X( a, b ) ((a) * (b)) 

If priority is not an issue, brackets of any type are not mandatory, although brackets may be required depending on the semantics of the macros - if, for example, you want to create a local variable,

+1
source

Source: https://habr.com/ru/post/1308003/


All Articles