“()”如何在C ++中将语句转换为表达式? [重复]

时间:2022-02-02 18:19:40

This question already has an answer here:

这个问题在这里已有答案:

I have the following code:

我有以下代码:

int main() {
    int i=0;
    int j=({int k=3;++i;})+1; // this line
    return 0;
}

It compiles and runs. If I remove the () from "this line", then it doesn't compile.

它编译并运行。如果我从“this line”中删除(),那么它就不会编译。

I'm just curious what syntax rule is being applied here.

我只是好奇这里应用了什么语法规则。

The {} contains 2 statements, and the last statement indicates the "return" value of this code block. Then why does it need an extra () pair to make this return value usable?

{}包含2个语句,最后一个语句表示此代码块的“返回”值。那为什么它需要一个额外的()对来使这个返回值可用?

1 个解决方案

#1


36  

That's a statement expression, and it's a GCC-specific extension.

这是一个声明表达式,它是GCC特定的扩展。


From the linked reference:

从链接参考:

A compound statement enclosed in parentheses may appear as an expression in GNU C. This allows you to use loops, switches, and local variables within an expression.

括在括号中的复合语句可能在GNU C中显示为表达式。这允许您在表达式中使用循环,开关和局部变量。

A compound statement is a curly-brace enclosed block of statements.

复合语句是一个大括号括起来的语句块。

#1


36  

That's a statement expression, and it's a GCC-specific extension.

这是一个声明表达式,它是GCC特定的扩展。


From the linked reference:

从链接参考:

A compound statement enclosed in parentheses may appear as an expression in GNU C. This allows you to use loops, switches, and local variables within an expression.

括在括号中的复合语句可能在GNU C中显示为表达式。这允许您在表达式中使用循环,开关和局部变量。

A compound statement is a curly-brace enclosed block of statements.

复合语句是一个大括号括起来的语句块。