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

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


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.

Share
Improve this question

5

  • 5

    It is a gcc extension IIRC. not standard C++.

    – Jarod42

    yesterday

  • 1

    Doesn't compile for me, even when I add sensible definitions for key and container. Could you supply an example without any missing parts?

    – john

    yesterday

  • 2

    It is a compiler extension gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html

    – n. m. could be an AI

    yesterday

  • default is a keyword. Even if the statement expression is removed, how can it compile it != container.end() ? it->second : default;?

    – 273K

    yesterday


  • Better question: How is this not standard yet? It's been available in Rust for ages now, albeit with less silly syntax.

    – Silvio Mayolo

    1 hour ago

2 Answers
2

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

Share
Improve this answer

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.

    – Daniel

    1 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.

Share
Improve this answer

1

  • 1

    You could've mentioned a full capture lambda as did Jarod.

    – Red.Wave

    13 hours ago



Not the answer you're looking for? Browse other questions tagged

or ask your own question.

Leave a Reply

Your email address will not be published. Required fields are marked *