case里面定义的变量是否持有它的价值

case里面定义的变量是否持有它的价值

本文介绍了一个在switch / case里面定义的变量是否持有它的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以在switch语句中创建一个变量,而不是初始化。

I know that it is possible to create, but not initalize, a variable inside a switch-statement. But I wonder if a created variable remains in memory, during subsequent executions of the switch-statement?

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

I assume the variable named cnt is newley created every time the switch-statement is executed. Therefore the value of cnt is always undefined, until the code inside a case label assigns a value!

#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;
}

但是至少在我的机器上, cnt 在switch-statement中定义它的值。我假设这是一个假阳性,我的系统是(坏运气)访问总是相同的内存区域。

But at least on my machine and during my tests, the variable cnt defined within the switch-statement persists it's value. I assume this a false positive and my system is (bad luck) accessing always the same memory region?

输出(GCC 4.9):

Output (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

谢谢

推荐答案

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

The compiler does not initialize the variable explicitly. So it has a value that is stored in the memory allocated for the variable. But according to the C++ Standard the variable is created each time when the control is passed to the switch statement.

事实上,没有什么能防止编译器在某些情况下使用相同的内存

In fact nothing prevents the compiler to use the same memory in some other code block included in the range-based for compound statement.

根据C ++标准

这篇关于一个在switch / case里面定义的变量是否持有它的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 08:36