0

I have a code block that I'm trying to convert from PHP to C++ and the compiler is getting hung up on my switch statements.

I have something along the lines of:

switch(//Some int)
{
    case 1:
    default:
        int32 x = 1;
        doSomething(x);
        break;
    case 2:
        doSomething(3);
        break;
}

And this is throwing errors:

error C2360: initialization of 'x' is skipped by 'case' label


I seem to be able to fix this by declaring and initializing the variables outside of the switch statement, but why is this? What's the problem with creating temporary variables in the scope of a switch statement?


Just for further clarification, I am only attempting to use x in that one call to doSomething(x). I don't attempt to use it outside of the switch statement's scope.

Liftoff
  • 24,717
  • 13
  • 66
  • 119

1 Answers1

1

Try adding {}:

default:
{
    int32 x = 1;
    doSomething(x);
    break;
}

According to the standard:

It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps91 from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless ....

void f() {
    // ...
    goto lx; // ill-formed: jump into scope of a
        // ...
    ly:
        X a = 1;
        // ...
    lx:
        goto ly; // OK, jump implies destructor
                 // call for a followed by construction
                 // again immediately following label ly
}

91) The transfer from the condition of a switch statement to a case label is considered a jump in this respect.

AlexD
  • 32,156
  • 3
  • 71
  • 65