C 块变成表达式: ( {int a = 1; int b = 2; a+b;} ) equals 3
在阅读http://en.wikipedia.org/wiki/C_preprocessor#Multiple_evaluation_of_side_effects时,我遇到了这个例子:
\#define max(a,b) \
({ typeof (a) _a = (a); \
typeof (b) _b = (b); \
_a > _b ? _a : _b; }) // WHY DOES THIS LINE WORK?
您可以像函数一样使用它,即 max(1,2)
是一个表达式计算结果为 2。
我的问题是,({ statment-list last-expression; })
构造如何计算为最后表达式的值?具体来说,a 的作用是什么?这个构造的解析树是什么样的?我认为 { }
总是意味着复合语句,并且语句没有值。我尝试深入研究C语法,但仍然无法解决这个问题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个名为语句表达式的 GCC 扩展。这不是标准C。
This is a GCC extension called Statement Expressions. It's not standard C.