Try reordering your cases:
switch(myVar)
{
default:
int b = 42; // error
break;
case 0:
int a = 12; // ok
}
Now you will see the compiler complain about b
, and not a
. There is nothing magical about default
, it's just that if you define the variable in the last case statement, then there is no way to skip over the initialization of that variable, and so it is perfectly fine to do so.
You can always scope your cases, so that the variables can't be accessed outside of a case, if that was your intention:
switch(myVar)
{
case 0: {
int a = 12;
}
break;
default:
int b = 42;
}