Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional initialization in switch

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

like image 430
patentfox Avatar asked Nov 16 '12 11:11

patentfox


People also ask

Can we give condition in switch case?

In a switch statement, we pass a variable holding a value in the statement. If the condition is matching to the value, the code under the condition is executed. The condition is represented by a keyword case, followed by the value which can be a character or an integer.

Can you initialize variables in a switch statement?

The variable can be declared, but it cannot be initialized.

Is switch faster than if else?

A switch statement is significantly faster than an if-else ladder if there are many nested if-else's involved. This is due to the creation of a jump table for switch during compilation. As a result, instead of checking which case is satisfied throughout execution, it just decides which case must be completed.

Do you need break in switch statement C++?

5) The break statement is optional. If omitted, execution will continue on into the next case. The flow of control will fall through to subsequent cases until a break is reached.


1 Answers

1: Valid

 case 1:
        {
        X x1;
        break;
        }

If it doesn't hit the condition, x1 can't be used by any further statements, so there can't be a runtime error with this. x1 doesn't try to exist outside braces.


2: Invalid

 switch(i) {
    case 1:
        X x1; //don't break
        i = 2;
        ...
        ...
        ...
     case 2:
        x1.someOperation()

 }

In the above, if i was 2 initially, you'd hit x1.someOperation() before X x1 which 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.

like image 186
Anirudh Ramanathan Avatar answered Oct 04 '22 01:10

Anirudh Ramanathan