Code:
void func(int p) {
switch(p) {
case 1: {
int i;
/* Do something with i */
} break;
case 2: {
char msg[10];
/* Do something with msg */
} break;
}
}
This is fine - the scope of the variables is limited by the braces.
Though for the reasons you state, you should consider making each case a separate function to keep the body of the switch nice and simple. One recently memorable (for the wrong reasons) switch was way over 3000 lines long.
The problem Quzah is thinking of is this
Code:
void func(int p) {
switch(p) {
int badvar = 0;
case 1: {
int i;
/* Do something with i */
} break;
case 2: {
char msg[10];
/* Do something with msg */
} break;
}
}
The problem is, despite what it looks like, badvar will never be initialised (cases are labels, and the switch is an organised goto). But the variable will still exist non the less.
gcc for example reports
warning: unreachable code at beginning of switch statement