Why do I get a warning when I declare the same variable name inside different cases of a switch-case.
switch()
{
case 1:
int a;
break;
case 2:
int a;
break;
}
Is there a way to do this without getting a warning. (Without putting it before the switch - case)
The reason is that the lexical scope of both declarations is the entire switch body; all the cases share that scope.
That is, in terms of lexical scope, it's like writing
{
int a;
int a;
}
The solution is to enclose the declarations in another braced scope.
switch(whatever)
{
case 1:
{
int a;
break;
}
case 2:
{
int a;
break;
}
}
(Whether you put the break
inside or outside the braces is mostly a matter of taste. I prefer to include the entire case.)
This works for the same reason that this "switch-free" snippet works:
{
{
int a;
}
{
int a;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With