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