7

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.

Community
  • 1
  • 1
vardhan
  • 75
  • 6
  • 4
    Dupes: [Oct 2009](http://stackoverflow.com/questions/1635549/in-what-versions-of-c-is-a-block-inside-parenthesis-used-to-return-a-value-valid) [May 2010](http://stackoverflow.com/questions/2892981/weird-initialization-in-c) [Jan 2010](http://stackoverflow.com/questions/2075930/more-information-on-in-c) – Martin York Dec 18 '10 at 00:12

1 Answers1

16

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

osgx
  • 90,338
  • 53
  • 357
  • 513
  • 1
    Currently (gcc 4.4.5), for C, `-ansi` is equivalent to `-std=c89` (and `-std=c++98` for C++). Some other useful options are `-std=c99`, `-std=gnu89`, `-std=gnu99`, `-std=c++0x`, `-std=gnu++0x`. – pmg Dec 18 '10 at 00:10
  • @pmg, If you know, will the "statement exprs" included in some coming standard? – osgx Dec 18 '10 at 00:12
  • 2
    Hmm ... this [PDF on the open-std site](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1229.pdf) hints to "statement expressions" becoming standard sometime. – pmg Dec 18 '10 at 00:19
  • @pmg, thanks. It is rather old pdf (2007-03). I will try to contact with some people, participating in C/C++ standards meetengs. – osgx Dec 18 '10 at 00:22
  • @Laurence Gonsalves, yes, but LLVM/clang and LLVM/GCC are. – osgx Dec 18 '10 at 00:29
  • @osgx: I haven't seen any indication that they will be. – R.. GitHub STOP HELPING ICE Dec 18 '10 at 01:34