Reputation: 2115
I read that initialization within cases of switch is supposed to give compiler error. But when I tried two different version. One is not giving out the error (Ex1), I can't understand why.
Ex 1:
switch (i)
{
case 1:
int k;
break;
case 2:
int j=3;
break;
}
Ex2:
switch (i)
{
case 1:
int k=3;
break;
case 2:
int j;
break;
}
Upvotes: 2
Views: 425
Reputation: 29022
In a switch block, every declaration that comes before a case
is available at that case
. The error occurs when there is a case
to which the switch
can jump to which is located after the initialization of a variable that you could access there. If that case
was jumped to, you could use the variable despite its initialization never occuring.
In the first example, there is no case
which would skip an initialization. The only initialization is int j=3;
which comes after every case
so it can't be skipped. k
is not initialized so its initialization can't be skipped.
In the second example,if i == 2
then k
's initialization would be skipped.
One solution is to define a scope for each case. Then, the variables defined for a case
is only accessible from that case
and the problem can't occur. For example :
void foo(int i)
{
switch (i)
{
case 1:
{
int k=3;
break;
}
case 2:
{
// k is not accessible here
int j;
break;
}
}
}
Upvotes: 6