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
After reading all answers and some more research I get a few things.
Case statements are only 'labels'
In C, according to the specification,
§6.8.1 Labeled Statements:
labeled-statement:
identifier : statement
case constant-expression : statement
default : statement
In C there isn't any clause that allows for a "labeled declaration". It's just not part of the language.
So
case 1: int x=10;
printf(" x is %d",x);
break;
This will not compile, see http://codepad.org/YiyLQTYw. GCC is giving an error:
label can only be a part of statement and declaration is not a statement
Even
case 1: int x;
x=10;
printf(" x is %d",x);
break;
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 {}
case 1:
{
int x=10;
printf(" x is %d", x);
}
break;
Or use dummy statement with label
case 1: ;
int x=10;
printf(" x is %d",x);
break;
Declare the variable before switch() and initialize it with different values in case statement if it fulfills your requirement
main()
{
int x; // Declare before
switch(a)
{
case 1: x=10;
break;
case 2: x=20;
break;
}
}
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:
switch(a)
{
printf("This will never print"); // This will never executed
case 1:
printf(" 1");
break;
default:
break;
}
See http://codepad.org/PA1quYX3.