Switch statement - are variables always retained?

I'm working on a piece of code in which I make use of a switch-statement, and I was hoping to have the following things clarified so I can advance:

(a) is the value of a global variable retained between switch states? (e.g. if in case1 X = 10, is X = 10 in case2 as well?)

(b) do local variables transition between cases? (e.g. if in case1 X is defined, can X be used in case2 without re-defining it?)

My code can run for a lengthy period of time - it may occasionally remain in a case for 10+ minutes. Does waiting for a lengthy period of time come with a risk of losing variable values?
Declare variables before switch; can define inside cases if you wish. Can't declare + define the same variable inside cases because I believe you could jump to another case with goto , though this is bad practice.

Edit: added the horrible goto. Please don't ever do this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>

using namespace std;

void Fun(int k)
{
    int i;
    switch (k)
    {
    case 3:
    really_bad_practice_dont_do_this:
        i = 11;
        cout << k << ' ' << i << ' ' << (k+i) << endl;
        break;

    case 4:
        i = 7;
        cout << k << ' ' << i << ' ' << (k-i) << endl;
        goto really_bad_practice_dont_do_this;
        break;

    case 5:
        i = 9;
        cout << k << ' ' << i << ' ' << (k*i) << endl;
        break;
        
    default:
        cout << "Unknown case '"<<k<<"'\n";
        break;
    }
}

int main() 
{
    for(int i=3; i<=6; ++i)
        Fun(i);

    return 0;
}

3 11 14
4 7 -3
4 11 15
5 9 45
Unknown case '6'
Last edited on
a) If I understood you correctly, you don't understand the switch statement :)
A switch statement is similar to nested if statements.
so..

int x = 10;
switch (x)
case 1:
//does not happen, x is not 1
case 10:
//happens ...
after all that x is still 10, unless you changed it in the case statements explicitly. The cases just check to see IF x is a value, it does not SET a value. The same is true for any other variable in your code, the above code would not modify y either, unless you explicitly assign it inside a case it won't change.

b) it is best if you DO NOT declare locals in a case statement. They can become very wonky. The standard c++ rules work: variables declared inside {} pairs are scoped to inside that {} pair, so proper use of them will properly give the correct scope for each case. So it will work as expected if you apply braces. You should NOT declare a local in one case and use it in another, even if you can get it working (you can) it is error prone in that editing the code later can break things, the code can be confusing to read and work with, and its just generally a bad idea.

an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
int x = 3;
switch(x)
{
    
  case 1: int y;
  case 2: y = 3;
  case 3: y = 5;  
  cout << y << endl;
};
}

that compiled and ran for me, printing 5.
It worked fine -- I did not expect that, using g++ c17 options.
I still think it is a bad thing to do as far as reading and following the intent.
if you put {} around the int y statement, it does NOT compile anymore.
If you put breaks after the case 1 and case 2, it does NOT compile anymore.
so it is 'fragile' to being edited, at the very least, to do this.

c) run time won't lose anything. Ive had programs that ran for months on end. Being in a case has no effect on this either. The risk of losing variables is the 'ram' risk that all programs face... if a long running program is killed by power outage or malfunction etc you lose anything not saved to a file and have to start over. Long running programs should save their state periodically to protect against this.

Last edited on
I probably need to explain it a bit better, as I see some difference in the way the switch state is normally, used, and the way I use it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
enum State {ONE, TWO, THREE};
State state = ONE;

int x;

void setup() {
...
}

void loop() {
    switch(state) {
    
    case ONE:
        x = 10;

    case TWO:
        ...

    case THREE:
        ...

}


In this case, if in case ONE I have x = 10, and then jump to case TWO, will x always remain 10? Can I indefinitely jump between cases for however long of a period, and will x always remain 10 until I give it a new value it?

I will hold off on declaring variables locally, thanks for the heads up.
Last edited on
if you are using fall through (no breaks) it will assign x to 10 and x will retain its value of 10 until changed. Its like the laws of physics... a variable assigned a value will retain that value until assigned something else by another line of code. Or something like that :)

I mean we can jump off the deep end of the pool an go VOLATILE on something but that is not worth talking about unless you are really out there doing weird stuff. You can change a variable with a buffer/pointer mistake (or intentional hackery) without an assignment statement as well, but I assume you are writing reasonable code and not intentionally writing this kind of junk? If writing normal, sane c++ the first paragraph is all you needed to know!
Last edited on
Yes, your assumption is correct. Still eventually you'd want to think how to redesign to avoid global vars. And why is "state" global and not a parameter of the function?
I wouldn't make it 'fall through', but put something like:

1
2
3
4
case ONE:
    x = 10;
    state = THREE;
    break;


as I don't want it to go through the cases in order (e.g. it could go ONE, THREE, FIVE, NINE, THREE, TWO). The exact cases it goes through depends on external factors (i.e. time of the day, sensor readings)


What's the reason for wanting to avoid global vars?

Last edited on
Topic archived. No new replies allowed.