这是什么C++在需要表达式的地方放置一个大括号包围的块的语法?
我遇到了这个奇怪的 C++ 程序。
#include <iostream>
using namespace std;
int main()
{
int a = ({int x; cin >> x; x;});
cout << a;
}
谁能解释一下发生了什么事吗?这个构造叫什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它将用户输入值分配给
a
并将其打印出来。它是通过使用语句表达式
来完成的。语句表达式是一个 gnu gcc 编译器扩展 并且不受 C/C++ 标准支持。因此,任何使用语句表达式的代码都不符合标准且不可移植。
IBM XL C/C++ v7.0 还支持语句表达式和语句表达式。它的文档恰当地解释了它们:
语句表达式:
始终通过在 GCC 中选择标准来编译代码:使用选项
-ansi
、-std=c90
或-std=iso9899:1990
之一>,-std=c++03
,-std=c++0x
;要获得标准所需的所有诊断信息,您还应该指定-pedantic
(如果您希望它们是错误而不是警告,则应指定-pedantic-errors
)。It assigns user input value to
a
and prints it out. it is done by using aStatement Expression
.Statement Expressions are a gnu gcc compiler extension and are not supported by the C/C++ standards. Hence, any code which uses statement expression is not standard conforming and non-portable.
The IBM XL C/C++ v7.0 also support Statement Expressions & its documentation explains them aptly:
Statement Expressions:
Always compile your code by selecting a standard 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).它是 GCC 扩展。如果您想摆脱这样的东西(并且您确实想要),请使用
-pedantic
标志编译您的代码。It's a GCC extension. Compile your code with the
-pedantic
flag if you want to get rid of stuff like this (and you really do want to).它创建一个内联作用域,在其中声明
x
,从标准输入读取它,整个语句最终计算为x
,它被分配给a.
逗号运算符的工作原理类似,但不需要单独的作用域。例如:
也会做同样的事情。所有以逗号连接的语句将顺序执行,整个表达式的结果将设置为最右边操作数的值。
It creates an inline scope, declares
x
within it, reads it from the standard input and the whole statement finally evaluates tox
, which is assigned toa
.The comma operator works similarly, although it doesn't require a separate scope. For example:
would do the same. All the statements connected with commas will be executed sequentially, and the result of the whole expression will be set to the value of the rightmost operand.
我不相信这是标准的 C++。它可能是一个特定于编译器的扩展,允许内部范围计算一个值。
I don't believe that this is standard C++. It's probably a compiler-specific extension that allows an inner scope to evaluate to a value.