4

What does a statement such as this mean ?

int x  = ( { int a; scanf( "%d", &a ); a ; } ) ;

It compiles and runs equivalent to :

int x;
scanf( "%d", &x );

It seems to be like some kind of anonymous function call or something, but I'm not sure. I have not come across statements like ({}) before, and I am unable to find any explanations online. Any help would be very much appreciated, thank you :)

Context:

This is the code that you get when the macros in the following code are expanded :

#define SI ({int a;scanf("%d",&a);a;});
int x = SI;

This is the code used by someone in a programming competition.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
arya
  • 565
  • 1
  • 6
  • 17
  • Is that programming competition the [IOCCC](http://www.ioccc.org/)? – ObscureRobot Oct 27 '11 at 06:44
  • @ObscureRobot: actually, in programming competitions you see lots of such macros, it's simply for reading the input easier and faster (time is often very limited so you don't want to waste it with "nice" wrappers). Doesn't have to be an IOCCC comp necessarily, I've written enough ugly code myself in such comps :p. Here probably some idiot thought macros were fasters than inlines... – KillianDS Oct 27 '11 at 06:49
  • The real question: why not make it an inline function... ? – Matthieu M. Oct 27 '11 at 06:50
  • possible duplicate of [Weird C++ Syntax](http://stackoverflow.com/questions/6305396/weird-c-syntax) – Luchian Grigore Oct 27 '11 at 06:54

1 Answers1

7

It is an Statement Expression.
It as an compiler extension supported by GCC and it is not Standard C++,hence it is non portable.
If you compile your code with the -pedantic flag it will tell you so.

This answer of mine talks about it in detail.

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • Just noticed that the Q was re-tagged to just `C`,So to be clear `Statement Expressions` are not Standard C or Standard C++. – Alok Save Oct 27 '11 at 06:55
  • What one maybe can mention is the reason for using it. For "void" macros that require multiple statements you can use the do-while-loop-construct to make the macro "behave" like a function call. This is portable, but when you need to return a value, this is the only possible way to achieve it (afaik). – flolo Oct 27 '11 at 07:09