• Advertisement
Sign in to follow this  

Variable initializations in "switch/case"?

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