什么是这个C ++语法,将一个括号包围的块,期望一个表达式? [英] What's this C++ syntax that puts a brace-surrounded block where an expression is expected?

查看:211
本文介绍了什么是这个C ++语法,将一个括号包围的块,期望一个表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个古怪的C ++程序。

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?

推荐答案

它将用户输入值赋给 a 并打印出来。它是通过使用语句表达式来完成的。

It assigns user input value to a and prints it out. it is done by using a Statement Expression.

语句表达式为 gnu gcc编译器扩展 不受C / C ++标准支持。因此,使用语句表达式的任何代码都是非标准符合和不可移植的。

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.

IBM IBM XL C / C ++ v7.0还支持语句表达式它的文档记录正确地解释它们:

The IBM IBM XL C/C++ v7.0 also support Statement Expressions & it's doccumentation explains them aptly:

语句表达式


复合语句是用大括号括起来的语句序列。在GNU C中,括号中的复合语句可能在所谓的语句表达式中作为表达式出现。



         .--------------.
         V              |
>>-(--{----statement--;-+--}--)--------------------------------><




语句表达式的值是最后一个简单表达式的值出现在整个构造中。如果最后一个语句不是一个表达式,那么结构的类型为void,并且没有值。

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.

GCC中的sandard,使用以下选项之一 -ansi -std = c90 -std = iso9899:1990 -std = c ++ 03 -std = c ++ 0x ;要获取标准所需的所有诊断,还应指定 -pedantic (或 -pedantic-errors 希望他们成为错误而不是警告)

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 ++语法,将一个括号包围的块,期望一个表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆