Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C block becomes expression: ( {int a = 1; int b = 2; a+b;} ) equals 3

While reading http://en.wikipedia.org/wiki/C_preprocessor#Multiple_evaluation_of_side_effects, I came across this example:

\#define max(a,b) \
   ({ typeof (a) _a = (a); \
       typeof (b) _b = (b); \
     _a > _b ? _a : _b; }) // WHY DOES THIS LINE WORK?

Which you can use exactly like a function, i.e. max(1,2) is an expression evaluating to 2.

My QUESTION is, How does ({ statment-list last-expression; }) construct evaluate to the value of last-expression? Specifically, what does a parse tree of this construct look like? I thought { } always meant a compound-statement, and statements have no values. I tried digging around in the C grammar and still couldn't figure this problem out.

like image 987
Kui Tang Avatar asked Aug 19 '11 05:08

Kui Tang


1 Answers

This is a GCC extension called Statement Expressions. It's not standard C.

like image 156
Mat Avatar answered Oct 24 '22 01:10

Mat