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?
After reading all answers and some more research I get a few things.
In C, according to the specification,
§6.8.1 Labeled Statements:
In C there isn't any clause that allows for a "labeled declaration". It's just not part of the language.
So
This will not compile, see http://codepad.org/YiyLQTYw. GCC is giving an error:
Even
this is also not compiling, see http://codepad.org/BXnRD3bu. Here I am also getting the same error.
In C++, according to the specification,
labeled-declaration is allowed but labeled -initialization is not allowed.
See http://codepad.org/ZmQ0IyDG.
Solution to such condition is two
Either use new scope using {}
Or use dummy statement with label
Declare the variable before switch() and initialize it with different values in case statement if it fulfills your requirement
Some more things with switch statement
Never write any statements in the switch which are not part of any label, because they will never executed:
See http://codepad.org/PA1quYX3.
Try this:
You can declare variables within a switch statement if you start a new block:
The reason is to do with allocating (and reclaiming) space on the stack for storage of the local variable(s).
New variables can be decalared only at block scope. You need to write something like this:
Of course, newVal only has scope within the braces...
Cheers, Ralph
I believe the issue at hand is that is the statement was skipped, and you tried to use the var elsewhere, it wouldn't be declared.