switch (false)
{
case true:
int jval;
break;
case false:
jval = 18;
cout << jval;
break;
}
Can anyone help me understand why I am able to access jval in this case ?
switch (false)
{
case true:
int jval;
break;
case false:
jval = 18;
cout << jval;
break;
}
Can anyone help me understand why I am able to access jval in this case ?
The cases are only labels, while break just means jump to the end of the switch scope block.
The lifetime of a variable is within the scope block ({ }
) from the place it was declared to the closing }
.
Also, if you don't put break and enter the first case
statement, the program flow will pass to the next one.
So the code in the second case
statement, got access to that variable.
If you want to not have access to it, guard it in another { }
scope block, to limit it's life time.
The variable scope is the part between curly brackets, not between case
and break
.
Thus, a variable declared in one case is in scope in all subsequent cases.
It may be clearer if you look at the equivalent formulation using goto
:
// "Jump table"
if (false == true)
goto case_true;
if (false == false)
goto case_false;
goto switch_end;
// switch body begins here.
{
case_true:
int jval;
goto switch_end;
case_false:
jval = 18;
cout << jval;
goto switch_end;
}
// switch ends here.
switch_end:
(This is more or less literally what a simple-minded compiler will translate a switch
into – a sequence of jumps and a trivially transformed body.)
Note that you will get an error if you try to initialise jval
:
switch (false)
{
case true:
int jval = 13; // Nope.
cout << jval
break;
case false:
jval = 18;
cout << jval;
break;
}
because you're not allowed to jump across a variable initialisation.