initialization in switch

Started by
2 comments, last by ajas95 18 years, 10 months ago
consider the code fragment below: case 1: int j = 1; break; VC give this error:error C2360: initialization of 'j' is skipped by 'case' label but if i write like this: case 1: int j; j = 1; break; it is successfully compiled why ?
Advertisement
try

case 1:
{
int j = 1;
}

as for why int j; is legal but not int j=1, i have no idea.
Quote:Original post by neverland
VC give this error:error C2360: initialization of 'j' is skipped by 'case' label
why ?


It's because of variable scope issues. You cannot declare a variable inside a switch statement because the compiler does not know if that statement will be executed or not, so it will not know wether or not to create that variable. That's why it gives you an error that the variable initialization is skipped, which means that you are declaring a variable that might or might not be actually created.
So, if it isn't explicitly clear from the previous posts:

You can declare a variable in a case statement, but only if you have the wavy-brackets {}.

case 2:
{
int j = 0;
break;
}

because this defines a scope (lifetime) for the variable. However, if you declare in this manner, you can't use the variable outside the case expression.

Your alternative would be to declare (and initialize!) the variable before the switch statement. Then any of your case statements can use that variable, and the variable can be used after the switch statment has finished.

This topic is closed to new replies.

Advertisement