为什么这个有效的C? -({123;})等于123 [英] Why is this valid C? --- ({123;}) evaluates to 123

查看:123
本文介绍了为什么这个有效的C? -({123;})等于123的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

是在括号内的块用于返回一个值有效的方法?在括号的哪个版本的c中,括号内的块用于返回有效值?

以下是典型MAX宏的类型安全版本(在gcc 4.4.5上有效):

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; })

在这里,我们看到此表达式max(a,b)返回表达式的结果

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

_a > _b ? _a : _b;

即使此表达式位于一个块中。因此,我进行了调查,发现这是有效的C:

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

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

有人可以解释为什么这是有效的语法,以及({语句})是?另外,您会注意到{123;}不是有效的表达式,而只有({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.

推荐答案

它不是有效的C99或C89或C ++。它是gcc扩展名,称为声明表达式。要使用gcc验证C代码,请添加选项 -ansi -pedantic -W -Wall-Wextra

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

语句表达式的文档在这里 http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html

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

此gnu扩展已在GNU代码和Linux中广泛使用,因此它不仅受GCC支持,而且还受现代编译器如Intel C ++编译器,Sun Studio,LLVM + clang的支持。 ,...

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, ...

这篇关于为什么这个有效的C? -({123;})等于123的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆