What is ({}) called in C++?

2k Views Asked by At

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.

2

There are 2 best solutions below

2
On BEST ANSWER

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;
}();
9
On

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.