Sign in to follow this  
mind in a box

Variable initializations in "switch/case"?

Recommended Posts

mind in a box    887
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
iMalc    2466
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

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