Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do parenthesis around braces enable preprocessor macro return values

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
like image 747
skyfire Avatar asked Nov 18 '25 16:11

skyfire


1 Answers

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.

like image 70
dbush Avatar answered Nov 21 '25 05:11

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!