Sign in to follow this  
neverland

initialization in switch

Recommended Posts

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 ?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this