What is this strange expression in GCC/Clang?

547 Views Asked by At

I have recently noticed an strange valid C/C++ expression in GCC/Clang which I have never seen before. Here is the example in C++, but similar expression works in C too:

int main(){
    int z = 5;
    auto x = ({z > 3 ? 3 : 2;}); // <-- expression
    std::cout << x;
}

What it does is somehow obvious, but I like to know what it is called. Since it does not worth in MSVC, I guess it is a non-standard extension. But is there anything that works for MSVC too? especially in C?

2

There are 2 best solutions below

1
On BEST ANSWER

It's called statement expr, used in GCC. Your expression ({z > 3 ? 3 : 2;}) can be translated to

if (z > 3) {x = 3;} else {x = 2;}

From documentation:

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.

In other word, it provides the ability to put a compound statement in an expression position.

Related post :

1
On

It is called conditional operator . Return will be depend on condition either condition is true or false.

But in this case: auto x = ({z > 3 ? 3 : 2;}); // <-- expression

if Z is greater than 3 returns 3 otherwise 2.

Basic syntax : Expression1? expression2: expression3;