Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this strange expression in GCC/Clang?

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?

like image 695
Afshin Avatar asked Oct 17 '25 11:10

Afshin


1 Answers

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 :

  • Emulating GCC Statement Expressions

  • Use of ({ ... }) brackets in macros to swallow the semicolon

like image 155
silverfox Avatar answered Oct 19 '25 01:10

silverfox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!