Reviewing some 3rd party C code I came across something like:
switch (state) {
case 0:
if (c=='A') { // open brace
// code...
break; // brace not closed!
case 1:
// code...
break;
} // close brace!
case 2:
// code...
break;
}
Which in the code I was reviewing appeared to be just a typo but I was surprised that it compiled with out error.
Why is this valid C?
What is the effect on the execution of this code compared to closing the brace at the expected place?
Is there any case where this could be of use?
Edit: In the example I looked at all breaks were present (as above) - but answer could also include behaviour if break absent in case 0 or 1.
Not only is it valid, similar structure has been used in real code, e.g., Duff's Device, which is an unrolled loop for copying a buffer:
Since a
switchstatement really just computes an address and jumps to it, it's easy to see why it can overlap with other control structures; the lines within other control structures have addresses that can be jump targets, too!In the case you presented, imagine if there were no
switchorbreaks in your code. When you've finished executing thethenportion of aifstatement, you just keep going, so you'd fall through into thecase 2:. Now, since you have theswitchandbreak, it matters whatbreakcan break out of. According to the MSDN page, “The C break statement”,Since the nearest enclosing do, for, switch, or while statement is your switch (notice that if is not included in that list), then if you're inside the
thenblock, you transfer to the outside of theswitchstatement. What's a bit more interesting, though, is what happens if you entercase 0, butc == 'A'is false. Then theiftransfers control to just after the closing brace of thethenblock, and you start executing the code incase 2.