Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why this works: C++ last statement as result of expression [duplicate]

Tags:

c++

I found strange macros in a driver implementation that I can't explain to myself. Simplified example is:

cout << ({int i=0; while(i<10) {++i;} i;}) << endl;

It will output 10.

But why this does expression become an rvalue at all? It seems to work in C and in C++.

Can someone explain me? Pointing to keywords and to reference will be great.

like image 987
johngull Avatar asked Dec 24 '15 13:12

johngull


1 Answers

The is a GCC extension:

A compound statement enclosed in parentheses may appear as an expression in GNU C.

The last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct.

like image 182
Karoly Horvath Avatar answered Oct 21 '22 16:10

Karoly Horvath