跳转绕过 switch 语句中的变量初始化

Aru*_*yan 6 c++ arrays string char switch-statement

出于某种目的,我的开关盒中需要一个std:: vector<char>std:: string。因此,我编写了以下虚拟代码来查看它是否有效:

#include <iostream>
#include <string>
int main() {
    int choice = 0;

    do {
        std:: cout << "Enter Choice" << std::endl;
        std:: cin >> choice;

        switch(choice) {
            case 1:
                std::cout << "Hi";
                break;

            case 2:
                std::string str;
                std::cin >> str;
                break;

            case 3: //Compilation error, Cannot jump from switch statement to this case label
                std::cout << "World" << std:: endl;
                break;

            default:
                std:: cout << "Whatever" << std:: endl;
        }

    } while(choice != 5);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

好吧,我有点明白这str是一个std:: string类型的对象。所以,我试图跳过这个变量初始化。

那么为什么定义C风格的字符串不会导致编译错误:

#include <iostream>
#include <string>
int main() {
    int choice = 0;

    do {
        std:: cout << "Enter Choice" << std::endl;
        std:: cin >> choice;

        switch(choice) {
            case 1:
                std::cout << "Hi";
                break;

            case 2:
                char str[6];
                std::cin >> str;
                break;

            case 3:
                std::cout << "World" << std:: endl;
                break;

            default:
                std:: cout << "Whatever" << std:: endl;
        }

    } while(choice != 5);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如何使第一个代码起作用?

joh*_*ohn 12

只需使用一对额外的大括号为变量创建一个新块

        case 2:
        { // <-- start new block for str
            std::string str;
            std::cin >> str;
            break;
        } // <-- end of block, str will be destroyed here
Run Code Online (Sandbox Code Playgroud)

  • 我认为这就是意图,否则为什么要在 switch 语句中声明它呢? (3认同)
  • 我想值得添加一个提示,即变量应该在其最内部的作用域中声明,该作用域最多只跨越预期的生命周期。在某些情况下,为变量的明确定义的生命周期添加额外的范围甚至很有用。(例如,推荐用于锁守护者或其他 RAII 事件。) (3认同)

yep*_*ons 6

char str[6];是默认初始化的。对于具有自动存储持续时间(“在堆栈上分配”)的简单值的 C 数组,它意味着“根本没有初始化”,所以我想这不是错误。

但是,如果像 那样初始化数组char str[6] = {},则会产生错误。

我建议您添加额外的花括号,以便str在它自己的范围内并且在进一步的case语句中不可见:

#include <iostream>
#include <string>
int main() {
    int choice = 0;

    do {
        std:: cout << "Enter Choice" << std::endl;
        std:: cin >> choice;

        switch(choice) {
            case 1:
                std::cout << "Hi";
                break;

            case 2: {  // Changed here
                std::string str;
                std::cin >> str;
                break;
            }
            case 3: // `str` is not available here, no compilation error
                std::cout << "World" << std:: endl;
                break;

            default:
                std:: cout << "Whatever" << std:: endl;
        }

    } while(choice != 5);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在哪里放置括号是样式偏好。