# Variable initializations in "switch/case"?

## 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 on other sites
Hodgman    51234
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 on other sites
Aha! Thank you :)

##### 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.