-2

Why does case 2 get evaluated twice in this for loop?

for (int x = 0; x <4; x++)
{
    switch (x)
    {
        case 2: printf("%d", x);
        case 0: printf("%d", x);
        default: break;
        case 3: printf("%d", x);
    }
}

edit: I forgot to add that this is not a legitimate piece of code. Just something that came up in my friends job exam last week.

Ozymandias
  • 839
  • 1
  • 8
  • 13
  • You want to add `break` at the end of each `case`. Otherwise it's not going to work as intended and hit every case until a `break` is found. – Spencer Wieczorek Apr 11 '18 at 22:57

2 Answers2

6

Case 2 doesn't get evaluated twice: it is evaluated exactly once. However, when you don't end a case with the break statement, instead of leaving the switch, execution continues to the next case.

In other words, when x is 2, execution jumps to case 2 and call printf("%d", x) with x = 2. Then, execution falls through to case 0, and calls printf("%d", x) with x still equal to 2. Then, execution falls through to the default case, where it hits a break statement and finally leaves the switch.

zneak
  • 134,922
  • 42
  • 253
  • 328
  • So when x = 2, case 0 is also executed even thought the condition is not satisfied? – Ozymandias Apr 11 '18 at 23:02
  • 3
    In C, a `case` is not a condition that guards execution. It's more like a `goto` label. – zneak Apr 11 '18 at 23:04
  • @Ozymandias `case 0` is coded below `case 2`. Without a `break`, execution flow starting in `case 2` falls through to `case 0`. Swap the order of the cases, and you won't see `case 0` executed anymore when `x=2`, but you will see `case 2` executed when `x=0` – Remy Lebeau Apr 12 '18 at 07:29
1

It doesn't. There's no break on those cases. That's why it prints case 2 then case 0.

Kolt Penny
  • 164
  • 1
  • 13