Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this valid C? --- ({123;}) evaluates to 123 [duplicate]

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.

like image 317
vardhan Avatar asked Dec 17 '10 23:12

vardhan


1 Answers

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, ...

like image 62
osgx Avatar answered Nov 15 '22 06:11

osgx