In Stroustrup's example, what does the colon mean in "return 1 : 2"?

C++Syntax

C++ Problem Overview


I don't understand one particular use of a colon.

I found it in the book The C++ Programming Language by Bjarne Stroustrup, 4th edition, section 11.4.4 "Call and Return", page 297:

void g(double y)
{
  [&]{ f(y); }                                               // return type is void
  auto z1 = [=](int x){ return x+y; }                        // return type is double
  auto z2 = [=,y]{ if (y) return 1; else return 2; }         // error: body too complicated
                                                             // for return type deduction
  auto z3 =[y]() { return 1 : 2; }                           // return type is int
  auto z4 = [=,y]()−>int { if (y) return 1; else return 2; } // OK: explicit return type
}

The confusing colon appears on line 7, in the statement return 1 : 2. I have no idea what it could be. It's not a label or ternary operator.

It seems like a conditional ternary operator without the first member (and without the ?), but in that case I don't understand how it could work without a condition.

C++ Solutions


Solution 1 - C++

It's a typo in the book. Look at Errata for 2nd and 3rd printings of The C++ Programming Language. The example must be like below:

auto z3 =[y]() { return (y) ? 1 : 2; }

Solution 2 - C++

Looks to me like a simple typo. Should probably be:

auto z3 =[y]() { return y ? 1 : 2; }

Note that since the lambda doesn't take any parameters, the parens are optional. You could use this instead, if you preferred:

auto z3 =[y] { return y ? 1 : 2; }

Solution 3 - C++

return 1 : 2; is a syntax error, it is not valid code.

A correct statement would be more like return (y) ? 1 : 2; instead.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPiockñecView Question on Stackoverflow
Solution 1 - C++273KView Answer on Stackoverflow
Solution 2 - C++Jerry CoffinView Answer on Stackoverflow
Solution 3 - C++Remy LebeauView Answer on Stackoverflow