Question

I just found out the hard way an inline if (A?B:C) does not work as expected in a switch statement.

where A a boolean, B and C both integer unequal to 0. The result of this statement is 0 when placed inside a switch.

I found a stackoverflow post [1] where this behaviour was mentioned but I can not find any explanation why this doesn't work as I would expect. What is causing this?

For example:

int foo = 6;

switch(foo)
{
case 6:
  return 10 + true ? 2 : 4;
}

[1] Benefits of inline functions in C++?

Était-ce utile?

La solution

This is nothing to do with switch.

10 + true ? 2 : 4

is equivalent to:

(10 + true) ? 2 : 4.

If you want it to act like:

10 + (true ? 2 : 4)

then you will need to write it like that.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top