Home > Back-end >  why do parenthesis around braces enable preprocessor macro return values
why do parenthesis around braces enable preprocessor macro return values

Time:10-12

When I write a macro I like to enclose the definition in braces (i.e., { }) to prevent any potiential namespace clashes that may occur. However, in order to get a return value from the macro, the macro definition for some reason also needs to be wrapped in parenthesis. Omitting the surrounding parenthesis causes no value to be returned. Why is that?

For example

#define ADD1(x)    \
  ({int y = (x)   1; \
    y;})

int foo = 3;
int bar = ADD1(foo);
//
// versus
//
#define ADD1_BROKEN(x) \
  {int y = (x)   1;    \
   y;}

int baz = ADD_BROKEN(foo); // DOES NOT COMPILE

CodePudding user response:

What you have in your first macro is a expression statement which is a gcc extension. It allows for a block statement in a place where an expression is allowed, with the last statement in the block being the value of the expression.

The second case doesn't work because you're attempting to use a block statement as an expression which isn't allowed.

That being said, your particular example would work better as a simple expression:

#define ADD1(x) ((x)   1)

If you really need something complex that looks like a function, just make a function.

CodePudding user response:

Preprocessor macros are a text replacement - nothing more, nothing less. After preprocessing, the line

int bar = ADD1(foo);

expands into

int bar = ({int y = (x)   1; y;});

which is an expression statement; this is an extension offered by compilers like gcc - I don't think this would compile with -pedantic.

The broken version expands into

int baz = {int y = (x)   1; y;};

which is invalid declaration syntax.

  • Related