Possible Duplicate:
in what versions of c is a block inside parenthesis used to return a value valid?
The following is a type-safe version of a typical MAX macro (this works on gcc 4.4.5):
#define max(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
Here, we see that this expression, max(a,b) returns the result of the expression
_a > _b ? _a : _b;
even though this expression is in a block. So, I investigated, and found that this is valid C:
int a = ({123;}); // a is 123
Can someone explain why this is valid grammar and what the true behaviour of ({statements}) is? Also, you will notice that {123;} is not a valid expression, but only ({123;}) is.
It is not a valid C99 or C89 nor C++. It is gcc extension, called "Statement expression". For validating a C code with gcc add options -ansi -pedantic
. Also useful options are -W -Wall -Wextra
Docs for statement expressions are here http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
This gnu extension is widely used in GNU code and Linux, so it is supported not only by GCC, but also in modern compilers like Intel C++ compiler, Sun Studio, LLVM+clang, ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With