I want to know more about "Why can’t variables be declared in a switch statement?"
I read the post but i am not getting it exactly. You can just declare variable inside switch but to decalre and initialize a variable or to declare object of class it gives complie time error.
Please explain me....
You can still declare variables in switch statements, you just have to put curly brackets around the code after the case label. Compare the two examples below.
The switch statement doesn't accept arguments of type long, float, double,boolean or any object besides String.
Important points to C Switch CaseVariables are not allowed inside the case label, but integer/character variables are allowed for switch expression. Break and default are optional.
Essentially because the initialisation of the variable would be skipped if the label containing the variable initialisation was not hit. This would be bad because the compiler would then have to emit code that would destroy said variable if and only if the initialisation code had run.
For example:
class A
{
// has some non-trivial constructor and destructor
};
switch (x)
{
case 1:
A a;
break;
default:
// do something else
}
If the code had hit the default
, then a
would not have been initialised. The compiler would have to have been able to figure this out in advance. Probably for performance reasons, this was disallowed.
The simple fix is to introduce a new layer of scope:
class A
{
// has some non-trivial constructor and destructor
};
switch (x)
{
case 1:
{
A a;
}
break;
default:
// do something else
}
This makes it ok, the destruction of a
is now well defined.
There is a conflict here between language syntax and common sense. For us humans, it looks like this code (taken from 1800 INFORMATION's answer) should work fine:
class A
{
// has some non-trivial constructor and destructor
};
switch (x)
{
case 1:
A a;
break;
default:
// do something else
}
After all, the curly braces define the scope for a; it is only created if we enter case 1, it is destroyed immediately after leaving the case 1 block and it will never be used unless we enter case 1. In fact, the case labels and the break instruction do not separate scopes, so a exists in all the block afterwards, even though it is logically unreachable. And sure, there is no such thing as a case 1 block from a syntactic point of view.
If you think of the switch statement as a bunch of (structured) goto instructions in disguise, the scope problem becomes more evident:
{
if (x == 1)
goto 1;
else
goto default;
1:
A a;
goto end;
default:
// do something else
end:
}
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