Yytsi
Yytsi

Reputation: 424

Confusing switch statement behaviour

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!

Upvotes: 1

Views: 986

Answers (4)

alediaferia
alediaferia

Reputation: 2617

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:

Upvotes: 11

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

Upvotes: 3

user2807083
user2807083

Reputation: 2972

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.

Upvotes: 1

MaciekGrynda
MaciekGrynda

Reputation: 703

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;

Upvotes: 5

Related Questions