2

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?

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

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?

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

Thank you

Peter
  • 2,240
  • 3
  • 23
  • 37

1 Answers1

4

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.

According to the C++ Standard

2 Variables with automatic storage duration (3.7.3) are initialized each time their declaration-statement is executed. Variables with automatic storage duration declared in the block are destroyed on exit from the block (6.6).

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335