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

标签 c++ initialization 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.

关于c++ - 在 switch 语句中初始化变量 (int32),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29871375/

相关文章:

c++ - 将 C++ DLL 加载到调用另一个 DLL 中的函数的 matlab

c++ - 非 POD 类类型的聚合初始化?

c++ - 如何在 switch 语句中选择一系列值?

c++ - 引导文件编译错误

c++ - 在 CUDA 中将动态分配的二维数组从主机复制到设备

c++ - Visual Studio C++ "Multithreaded Debug DLL"与 "Multithreaded DLL"

java - 在 do{} 中初始化的变量不递增

c - 初始化一个二维字符串数组并打印

java - 为什么 java switch 语句不能处理 null,因为它有一个 "default"子句?

java - 如何将 enum 与 switch 语句一起使用?