问题
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.
回答1:
This is a GCC extension called Statement Expressions. It's not standard C.
来源:https://stackoverflow.com/questions/7117427/c-block-becomes-expression-int-a-1-int-b-2-ab-equals-3