Search code examples
c++gcc-statement-expression

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


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.


Solution

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