1

I saw this code and I expected the output to be 6, but I got 17.

int x = 3;
switch (x)
{
  case 1: { x += x; }
  case 3: { x += x; }
  case 5: { x += x; }
  default: { x += 5; }
}
std::cout << x;

Why does x become 17? Shouldn't it become 6 by selecting the case 3 and exiting the switch statement?

Even if it would go through the default case after the case 3, x would only be 11. The only way I see that x would become 17 is by going through case (1 & 3) or (3 & 5) + the default case. I don't see why it would work like that though.

Any direction on what's happening step-by-step would be great!

6
  • 4
    You forgot break Commented Jun 27, 2016 at 8:57
  • @GauravSehgal Arrgh! Well, that's the solution right there :D
    – Yytsi
    Commented Jun 27, 2016 at 8:59
  • 1
    This is why coding standard matters: some C++ coding standard does not allow write one-line code like this, and thus makes it easier to find break is forgot.
    – Mine
    Commented Jun 27, 2016 at 9:01
  • Downvoter, how is this a bad question?
    – Yytsi
    Commented Jun 27, 2016 at 9:03
  • possible duplicate stackoverflow.com/questions/5776253/… Commented Jun 27, 2016 at 9:06

4 Answers 4

11

When you don't use break in your switch case statement, the code doesn't stop at the matching case evaluation but proceeds executing all the other case statements below until a break is found or when the switch statement completes.

In this example the first matching case is executed for x == 3 and then it proceeds executing all of the below statements, leading to 17 as a result.

You can read more about the reasons for this here:

5

You forgot about break; instruction. When you switch-case c++ runs from first case that is true up to break. So your code goes like this:

int x = 3;
switch (x)
{
  case 1: { x += x; } // ignored
  case 3: { x += x; } // goes in
  case 5: { x += x; } // still executes, because of no break
  default: { x += 5; } // still executes, because of no break
}
std::cout << x;
3

Cases in switch statements fall through to the next one, unless you add a break. I.e., when you give it 3, it runs case 3, falls through to case 5, and then falls through to the default case.

To avoid this, add break; at the end of your cases:

int x = 3;
switch (x)
{
  case 1: { x += x; break; }
  case 3: { x += x; break; }
  case 5: { x += x; break; }
  default: { x += 5; break; }
}
std::cout << x;

See also

1

In c and c++ switch statement behaves like civilized goto statement. Every case is kind of label and execution goes to corresponding label and then go through other cases after. So you have to use break after every case if you don't want other cases executed after one.

Not the answer you're looking for? Browse other questions tagged or ask your own question.