Jump to content
  • Advertisement
Sign in to follow this  
mind in a box

Variable initializations in "switch/case"?

This topic is 3003 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

Hi all! Sometimes, when I want to initialize a variable in a "case" of a "switch", the compiler tells me, that the initialization was skipped because of the "case". Here is an example:
switch(Foo)
{
    case 1:
       int i=0;
       break;
}

while this works:
switch(Foo)
{
    case 1:
       int i;
       i=0;
       break;
}

So, its not a big problem, but I just would like to know if it is possible :)

Share this post


Link to post
Share on other sites
Advertisement
Declaring variables inside a switch is a little strange, so it's best to enclose them in some extra braces, like:
switch(Foo)
{
case 1:
{
int i=0;
break;
}
}

Share this post


Link to post
Share on other sites
It's because switch statements allow you to do stuff like this:
switch(Foo)
{
case 1:
int i=0;
cout << "A: " << i << endl;
case 2:
cout << "B: " << i << endl;
i=3;
cout << "C: " << i << endl;
break;
}
For which you'll note that Foo being 1 gives:
A: 0
B: 0
C: 3

But if Foo is 2 we get:
B: <random value>
C: 3

The warning is thus showing you that by jumping to case 2 the value of i is most likely not going to be as desired.
Compilers don't tend to bother working out if you actually are doing something like the above; they instead just complain regardless.

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!