TuukkaX TuukkaX - 1 year ago 109
C++ Question

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
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,
would only be 11. The only way I see that
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!

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download