3

In Lua, you can do this:

foo = a and b or c and d or e

Which is equivalent to (at least I am pretty sure it is equivalent to):

local foo = nil
if a then
foo = b
elseif c then
foo = d
else
foo = e
end

Is there anything equivalent or similar to this in C++?

pighead10
  • 4,155
  • 10
  • 34
  • 52

5 Answers5

6

I guess this is what you want:

foo = a ? b : (c ? d : e );
Hakan Serce
  • 11,198
  • 3
  • 29
  • 48
5

There's the ternary operator. It has funny precedence, so it's good practice to always parenthesize it.

bool foo = ( a ? b : ( c ? d : e ) )

Note that this only works if b, d, and e can reduce to the same type. If a is a double, d is a float and e is an int, your result will always be cast to a double.

jpjacobs
  • 9,359
  • 36
  • 45
robert
  • 33,242
  • 8
  • 53
  • 74
  • What's funny about `?:`'s precedence? It's lower than any non-assigning operator and higher than all assigning ones, and that's it. So you can easily leave out the outer parentheses. What's somewhat more funny is its _associativity_, that's why you need parens between nested `?:`s. – leftaroundabout May 26 '12 at 11:00
  • @leftaroundabout it doesn't have the precedence I would expect it to have. Example: http://stackoverflow.com/q/10007140/382471 – robert May 26 '12 at 11:03
  • The precedence is quite reasonable: it makes sense to write stuff like `foo = c=='x' ? x : y` or `foo = a||b ? x : y`, so it's got to have lower precedence than the logical- and comparison operators. — Also, I need to take back what I said about associativity: it's simply right-associative, so you can leave out the inner parens as well. Though you should spread the expression over three lines with suitable indentation then, otherwise it becomes unreadable. – leftaroundabout May 26 '12 at 11:21
2

You can use the ternary operator ?:

foo = a ? b : c ? d : e;
Peter Alexander
  • 53,344
  • 14
  • 119
  • 168
  • while it's not necessary to add brackets here, I would do so anyway to improve clarity -- the above code is just about readable with a bunch of single-letter variable names, but anything more complex than the example given would quickly become unmanageable. – Spudley May 26 '12 at 19:39
1

Not really. The main reason this works in Lua is because of dynamic typing- in C++ you could never really make it work. The closest you can get is the ternary operator, but it has srs limitations.

Puppy
  • 144,682
  • 38
  • 256
  • 465
-3

Use && in C or in C++ for and then and use || for or else

Use the ternary ?: for conditional expressions

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547