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.
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.
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;
}();
break
/continue
... –
Skurnik 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.
break
, continue
, and return
) is different between the two, because a lambda creates a completely new and distinct function scope while a statement expression is "just" one more statement of the enclosing function scope. –
Skurnik __once_and_then(someType x=y; z)
which would initialize x
, process the following, and then evaluate z
, which could be used to do things like acquire a lock, perform an action, and release the lock... –
Impetrate for
loop and a dummy flag, but the amount of compiler logic necessary to avoid generating extra machine code for that would be greater than the amount required to handle __once_and_then
. –
Impetrate © 2022 - 2024 — McMap. All rights reserved.
key
andcontainer
. Could you supply an example without any missing parts? – Unspeakabledefault
is a keyword. Even if the statement expression is removed, how can it compileit != container.end() ? it->second : default;
? – Replication