Change the switch variable inside the case

In the following code:

int i = 0;

switch(i)
{
    case 0:
        cout << "In 0" << endl;
        i = 1;
        break;
    case 1:
        cout << "In 1" << endl;
        break;
}

What will happen? Will it refer to undefined behavior?

+5
source share
4 answers

No undefined. But the value iis only checked when the code reaches switch (i). Therefore, it case 1:will be skipped (by the operator break;).

The keyword switchdoes not mean "run code when the value iis 0/1." This means, check that iRIGHT NOW, and run the code on it. I don't care what happens iin the future.

In fact, sometimes it’s useful to do:

for( step = 0; !cancelled; ++step ) {
    switch (step)
    {
        case 0:
            //start processing;
            break;

        case 1:
            // more processing;
            break;

        case 19:
            // all done
            return;
    }
}

case ( , next_state case state = next_state ).

+8

. . , , - switch.

+1

switch , 1, , case 1.

0

:

" 0"

even if you assign the value i = 1, it will not be reflected, because the switch does not work on iteration, this is a one-time choice, since a break will force it to exit the switch statement.

0
source

All Articles