I\'ve always wondered this - why can\'t you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring
A switch
block isn't the same as a succession of if/else if
blocks. I'm surprised no other answer explains it clearly.
Consider this switch
statement :
switch (value) {
case 1:
int a = 10;
break;
case 2:
int a = 20;
break;
}
It may be surprising, but the compiler will not see it as a simple if/else if
. It will produce the following code :
if (value == 1)
goto label_1;
else if (value == 2)
goto label_2;
else
goto label_end;
{
label_1:
int a = 10;
goto label_end;
label_2:
int a = 20; // Already declared !
goto label_end;
}
label_end:
// The code after the switch block
The case
statements are converted into labels and then called with goto
. The brackets create a new scope and it is easy to see now why you can't declare two variables with the same name within a switch
block.
It may look weird, but it is necessary to support fallthrough (that is, not using break
to let execution continue to the next case
).