11
I just read code like this:
auto value = ({
auto it = container.find(key);
it != container.end() ? it->second : default_value;
});
What is this ({})
called? I don’t think I’ve ever seen this before.
5
2 Answers
Reset to default
13
It is a gcc extension, so not standard C++,
it is statement expression.
Since C++11, you might use Immediately Invoked Function Expressions (IIFE)
with lambda instead in most cases:
auto value = [&](){
auto it = container.find(key);
return it != container.end() ? it->second : default_value;
}();
1
-
2
It is still not the same as lambdas since a return in statement expressions returns from the enclosing function and not the statement expression.
– Daniel1 hour ago
7
Even before C89 was published, the authors of gcc invented an extension called a "statement expression" which would have been a useful part of the Standard language. It takes a compound statement whose last statement is an expression, and executes everything therein, and then treats the value of the last expression as the value of the statement expression as a whole.
While some other compilers have options to support such gcc extensions, the Standard’s refusal to recognize features that aren’t widely use, combined with programmers’ reluctance to use features that aren’t recognized by the Standard, have created a decades-long "chicken and egg" problem.
1
-
1
You could've mentioned a full capture lambda as did Jarod.
– Red.Wave13 hours ago
Not the answer you're looking for? Browse other questions tagged
or ask your own question.
or ask your own question.
It is a gcc extension IIRC. not standard C++.
yesterday
Doesn't compile for me, even when I add sensible definitions for
key
andcontainer
. Could you supply an example without any missing parts?yesterday
It is a compiler extension gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
yesterday
default
is a keyword. Even if the statement expression is removed, how can it compileit != container.end() ? it->second : default;
?yesterday
Better question: How is this not standard yet? It's been available in Rust for ages now, albeit with less silly syntax.
1 hour ago
|