我遇到了这个奇怪的 C++ 程序.
#include 使用命名空间标准;int main(){int a = ({int x; cin >> x; x;});cout<<一个;}
谁能解释一下这是怎么回事?这个结构叫什么?
它将用户输入值分配给 a
并打印出来.它是通过使用Statement Expression
来完成的.
语句表达式是 gnu gcc 编译器扩展 不受 C/C++ 标准支持.因此,任何使用语句表达式的代码都是不符合标准且不可移植的.
IBM IBM XL C/C++ v7.0 也支持 Statement Expressions &它的文档恰当地解释了它们:
语句表达:
<块引用>复合语句是用大括号括起来的一系列语句.在 GNU C 中,括号内的复合语句可能作为表达式出现在所谓的 Statement expression
中.
.--------------.V |>>-(--{----statement--;-+--}--)--------------------------------><
<块引用>
语句表达式的值是出现在整个构造中的最后一个简单表达式的值.如果最后一条语句不是表达式,则构造的类型为 void 并且没有值.
始终通过在 GCC 中选择标准来编译您的代码,使用选项 -ansi
、-std=c90
或 -std=iso9899:1990 之一
, -std=c++03
, -std=c++0x
;要获得标准要求的所有诊断信息,您还应该指定 -pedantic
(或 -pedantic-errors
,如果您希望它们是错误而不是警告)
I came across this weird C++ program.
#include <iostream>
using namespace std;
int main()
{
int a = ({int x; cin >> x; x;});
cout << a;
}
Can anyone explain what is going on? What is this construct called?
It assigns user input value to a
and prints it out. it is done by using a Statement Expression
.
Statement Expressions are gnu gcc compiler extension are not supported by the C/C++ standards. Hence any code which uses statement expression is non standard conforming and non portable.
The IBM IBM XL C/C++ v7.0 also support Statement Expressions & it's doccumentation explains them aptly:
Statement Expressions:
A compound statement is a sequence of statements enclosed by braces. In GNU C, a compound statement inside parentheses may appear as an expression in what is called a
Statement expression
.
.--------------.
V |
>>-(--{----statement--;-+--}--)--------------------------------><
The value of a statement expression is the value of the last simple expression to appear in the entire construct. If the last statement is not an expression, then the construct is of type void and has no value.
Always compile your code by selecting a sandard in GCC, use one of the options -ansi
, -std=c90
or -std=iso9899:1990
, -std=c++03
, -std=c++0x
; to obtain all the diagnostics required by the standard, you should also specify -pedantic
(or -pedantic-errors
if you want them to be errors rather than warnings)
这篇关于将大括号包围的块放在需要表达式的位置的 C++ 语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!