NOTE: Please see edit to see why it's not a duplicate.
Note the use of ({..})
inside the print()
call.
#include <iostream>
#include <sstream>
using namespace std;
void print(const std::string& msg) {
cout << msg << endl;
}
int main() {
print(({
ostringstream s;
s << "hello";
s << " world";
s.str();
}));
}
This construct is used in the Linux kernel code--which is where I first encountered it--usually in complex macro definitions.
Turns out g++ will also compile this snippet with no warnings, even using -Wall -Wextra
.
Is this thing really standard C and C++ code? If so, how is it called, and where can I find it defined in the latest C++ (in particular) standard?
Additionally, if it's standard, is there anything one should keep in mind while using it in C++? For example, what are the copy/move semantics of the scope's "return value" (if you can call it that)? What are some possible drawbacks of using this construct? (Aside from some people not knowing or liking it.)
EDIT: There is this question which deals with ANSI C. Are compound statements (blocks) surrounded by parens expressions in ANSI C?
So now the question is rather, is it legit C99 or C++11?