Piockñec
Piockñec

Reputation: 1271

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

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.

Upvotes: 164

Views: 11676

Answers (3)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38549

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

Upvotes: 206

Remy Lebeau
Remy Lebeau

Reputation: 596652

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

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

Upvotes: 11

Jerry Coffin
Jerry Coffin

Reputation: 490198

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

Upvotes: 20

Related Questions