Jump to content
  • Advertisement
Sign in to follow this  

initialization in switch

This topic is 4738 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!