Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing switch variable inside a 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 invoke undefined behavior?

like image 222
Dani Avatar asked Nov 30 '11 22:11

Dani


People also ask

Can we declare variable inside switch case?

If a programmer declares variables, initializes them before the first case statement, and then tries to use them inside any of the case statements, those variables will have scope inside the switch block but will not be initialized and will consequently contain indeterminate values.

Can we use variables in switch case in C?

Important points to C Switch CaseVariables are not allowed inside the case label, but integer/character variables are allowed for switch expression. Break and default are optional.

Which variable Cannot be used in switch case?

Explanation: The switch/case statement in the c language is defined by the language specification to use an int value, so you can not use a float value.

How do you break into a switch case?

You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.


2 Answers

No undefined behavior. But the value of i is only tested when the code reaches switch (i). So case 1: will be skipped (by the break; statement).

The switch keyword does not mean "run code whenever the value of i is 0 / 1". It means, check what i is RIGHT NOW and run code based on that. It doesn't care what happens to i in the future.

In fact, it's sometimes 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;
    }
}

And changing the control variable inside a case block is extremely common when building a finite state machine (although not required, because you could set next_state inside the case, and do the assignment state = next_state afterward).

like image 136
Ben Voigt Avatar answered Oct 08 '22 04:10

Ben Voigt


You break out of this switch statement after you set it to 1 which is defined behavior so it will never enter case 1.

like image 22
Joe Avatar answered Oct 08 '22 04:10

Joe