What's this C++ syntax that puts a brace-surrounded block where an expression is expected?

江枫思渺然 提交于 2019-11-26 22:42:32

问题


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?


回答1:


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)




回答2:


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




回答3:


It creates an inline scope, declares x within it, reads it from the standard input and the whole statement finally evaluates to x, which is assigned to a.

The comma operator works similarly, although it doesn't require a separate scope. For example:

int x;
int a = (cin >> x, x);

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.




回答4:


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.



来源:https://stackoverflow.com/questions/6305396/whats-this-c-syntax-that-puts-a-brace-surrounded-block-where-an-expression-is

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