6

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Kui Tang
  • 195
  • 7
  • `42;` is a statement as well :-) – paxdiablo Aug 19 '11 at 05:50
  • 1
    Ah, but I suspect the OP knows that `42;` is a statement because it is a statement in Standard C. The statement expression is not in Standard C, however. – Ray Toal Aug 19 '11 at 05:52
  • Possible duplicate of [Are compound statements (blocks) surrounded by parens expressions in ANSI C?](https://stackoverflow.com/questions/1238016/are-compound-statements-blocks-surrounded-by-parens-expressions-in-ansi-c) – GSerg Jan 26 '20 at 16:25

1 Answers1

12

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

Mat
  • 202,337
  • 40
  • 393
  • 406
  • Statement expressions?! Sounds like a headache. – BoltClock Aug 19 '11 at 05:52
  • Thanks! Of course I should have actually read "both the typeof keyword, and the construct of placing a compound statement within parentheses, are non-standard extensions implemented in the popular GNU C compiler (GCC)." Oops. – Kui Tang Aug 19 '11 at 05:56
  • 2
    I like them. They allow to do intelligent stuff like this. :) – balki Aug 19 '11 at 08:39