Why is this valid C? — ({123;}) evaluates to 123 [duplicate]

大憨熊 提交于 2019-12-12 07:58:42

问题


Possible Duplicate:
in what versions of c is a block inside parenthesis used to return a value valid?

The following is a type-safe version of a typical MAX macro (this works on gcc 4.4.5):

#define max(a,b) \
({ __typeof__ (a) _a = (a); \
   __typeof__ (b) _b = (b); \
 _a > _b ? _a : _b; })

Here, we see that this expression, max(a,b) returns the result of the expression

_a > _b ? _a : _b;

even though this expression is in a block. So, I investigated, and found that this is valid C:

int a = ({123;}); // a is 123

Can someone explain why this is valid grammar and what the true behaviour of ({statements}) is? Also, you will notice that {123;} is not a valid expression, but only ({123;}) is.


回答1:


It is not a valid C99 or C89 nor C++. It is gcc extension, called "Statement expression". For validating a C code with gcc add options -ansi -pedantic. Also useful options are -W -Wall -Wextra

Docs for statement expressions are here http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html

This gnu extension is widely used in GNU code and Linux, so it is supported not only by GCC, but also in modern compilers like Intel C++ compiler, Sun Studio, LLVM+clang, ...



来源:https://stackoverflow.com/questions/4475786/why-is-this-valid-c-123-evaluates-to-123

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!