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
So far the answers have been for C++.
For C++, you can't jump over an initialization. You can in C. However, in C, a declaration is not a statement, and case labels have to be followed by statements.
So, valid (but ugly) C, invalid C++
switch (something)
{
case 1:; // Ugly hack empty statement
int i = 6;
do_stuff_with_i(i);
break;
case 2:
do_something();
break;
default:
get_a_life();
}
Conversly, in C++, a declaration is a statement, so the following is valid C++, invalid C
switch (something)
{
case 1:
do_something();
break;
case 2:
int i = 12;
do_something_else();
}