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 them close to first use is obviously a good thing) but the following still won't work:
switch (val)
{
case VAL:
// This won't work
int newVal = 42;
break;
case ANOTHER_VAL:
...
break;
}
The above gives me the following error (MSC):
initialization of 'newVal' is skipped by 'case' label
This seems to be a limitation in other languages too. Why is this such a problem?
My favorite evil switch trick is to use an if(0) to skip over an unwanted case label.
But very evil.
Consider:
In the absence of break statements, sometimes newVal gets declared twice, and you don't know whether it does until runtime. My guess is that the limitation is because of this kind of confusion. What would the scope of newVal be? Convention would dictate that it would be the whole of the switch block (between the braces).
I'm no C++ programmer, but in C:
Works fine. Declaring a variable inside a switch block is fine. Declaring after a case guard is not.
I just wanted to emphasize slim's point. A switch construct creates a whole, first-class-citizen scope. So it is posible to declare (and initialize) a variable in a switch statement before the first case label, without an additional bracket pair:
newVal exists in the entire scope of the switch but is only initialised if the VAL limb is hit. If you create a block around the code in VAL it should be OK.
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++
Conversly, in C++, a declaration is a statement, so the following is valid C++, invalid C
The entire section of the switch is a single declaration context. You can't declare a variable in a case statement like that. Try this instead: