In the switch-case statements declaration-with-initialization is invalid but declaration-and-then-assignment is allowed. As shown in the following code snippet.
What is difference between these two type of initializations from the compiler side? And why is the first type of initialization invalid and second type a valid one.
switch(val)
{
case 0:
int newVal = 42; //Invalid
break;
case 1:
int newVal2; //Valid
newVal2 = 42;
break;
case 2:
break;
}
Effectively, the rule is that you can't jump into a block past a declaration that has an initialization (or past the declaration of a non-POD type variable). The C++ standard says (C++03 §6.7):
int newVal = 42;
is a declaration that has an initializer (the= 42
part). The program is ill-formed because ifval
is1
or2
, you'll jump into the switch block past the initialization.int newVal2;
is also a declaration; becauseint
is a POD type and the declaration has no initializer, you can jump past this declaration.In fact, neither are legal C++. You cannot declare a variable in a switch case unless it is scoped:
The fact that your compiler permits case 1 is a defect of your compiler, or possibly an extension. At least, according to the standard.