Why can't variables be declared in a switch statement
-
I've always wondered this -why can't you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring them close to first use is obviously a good thing) but the following still won't work
-
I've always wondered this -why can't you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring them close to first use is obviously a good thing) but the following still won't work
You can, you just need to put them, and the code that uses them inside curly braces, thus:
switch (number)
{
case 1:
{
int i; // local to only this case statement
}
}Variables not inside such a block are considered to have the scope of the entire
switch
block. But if they are declared in a singlecase
statement there is a possibility that they would not get initialised safely. To make a variable available to multiplecase
statements it must be declared before theswitch
.