在开关/案例中定义的变量是否会持续它的值?

时间:2014-06-21 16:44:06

标签: c++ switch-statement

我知道可以在switch语句中创建变量,但不能初始化变量。但我想知道在后续执行switch语句期间,创建的变量是否仍保留在内存中?

我假设名为 cnt 的变量是 newley每次创建执行switch语句时。因此, cnt 的值始终未定义,直到案例标签内的代码分配值为止!

#include <iostream>
using namespace std;

int main() {
    int iarr[6] = {0, 1, 1, 1, 0, 1};

    for (int i : iarr) {
        switch (i) {
            int cnt;
            case 0:
                // it is illegal to initalize value, therefore we assign an
                // inital value now
                cout << "Just assign 0 to the variable cnt.\n";
                cout << (cnt = 0) << "\n";
                break;
            case 1:
                cout << "Increment variable cnt.\n";
                cout << ++cnt << "\n";
                break;
        }
    }

    return 0;
}

但至少在我的机器上和测试期间,switch-statement中定义的变量 cnt 仍然存在它的值。我认为这是误报,我的系统(运气不好)总是访问相同的内存区域?

输出(GCC 4.9):

$ g++ -o example example.cpp -std=gnu++11 -Wall -Wpedantic -fdiagnostics-color && ./example
Just assign 0 to the variable cnt.
0
Increment variable cnt.
1
Increment variable cnt.
2
Increment variable cnt.
3
Just assign 0 to the variable cnt.
0
Increment variable cnt.
1

谢谢

1 个答案:

答案 0 :(得分:4)

编译器不会显式初始化变量。因此它有一个存储在为变量分配的内存中的值。但是根据C ++标准,每次将控件传递给switch语句时都会创建变量。

实际上没有什么能阻止编译器在复合语句的基于范围的其他代码块中使用相同的内存。

根据C ++标准

  

2初始化具有自动存储持续时间(3.7.3)的变量   每次执行声明声明。变量与   在块中声明的自动存储持续时间在退出时被销毁   从块(6.6)。