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

后端 未结 4 1475
借酒劲吻你
借酒劲吻你 2020-11-30 02:50

I came across this weird C++ program.

#include 
using namespace std;
int main()
{
  int a = ({int x; cin >> x; x;});
  cout << a;         


        
4条回答
  •  孤独总比滥情好
    2020-11-30 03:18

    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)

提交回复
热议问题