在 switch 语句中初始化变量 (int32)

Initializing variables (int32) inside switch statement

我有一个代码块,我正在尝试将其从 PHP 转换为 C++,但编译器在我的 switch 语句上挂断了。

我有一些类似的东西:

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

这是抛出错误:

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


我似乎可以通过在 switch 语句之外声明和初始化变量来解决这个问题,但这是为什么呢?在 switch 语句范围内创建临时变量有什么问题?


为了进一步说明,我只是试图在对 doSomething(x) 的那个调用中使用 x。我不会尝试在 switch 语句的范围之外使用它。

尝试添加 {}:

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

根据标准:

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.