What#39;s this C++ syntax that puts a brace-surrounded block where an expression is expected?(将大括号包围的块放在需要表达式的位置的 C++ 语法是什么?)
问题描述
我遇到了这个奇怪的 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++ 语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将大括号包围的块放在需要表达式的位置的 C++ 语法是什么?


基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01