Search code examples
c++returnexpressionblock

How does "()" convert statements into expressions in C++?


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.

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?


Solution

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


    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.

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