Why does this code fragment run fine
void foo(int i)
{
switch(i) {
case 1:
{
X x1;
break;
}
case 2:
X x2;
break;
}
}
whereas the following gives compilation error (initialization of ‘x1’ is skipped by ‘case’ label)?
void foo(int i)
{
switch(i) {
case 1:
X x1;
break;
case 2:
X x2;
break;
}
}
I understand that using braces introduces a new scope, hence storage will not be allocated for x1 till we hit its opening brace. But x2 is still initialized inside a case label without enclosing braces. Should this not be an error too?
I think initialization of x2 can be conditionally skipped in both the code fragments
1: Valid
If it doesn’t hit the condition,
x1can’t be used by any further statements, so there can’t be a runtime error with this.x1doesn’t try to exist outside braces.2: Invalid
In the above, if
iwas2initially, you’d hitx1.someOperation()beforeX x1which would construct the object.If it was allowed to compile, it would throw a runtime error or not, depending upon whether the case:1 was executed before 2, (and the object was constructed). Hence, it is disallowed by the compiler.
The same is allowed with Plain Old Data types which cannot have a user-defined constructor.