Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execution of multiple cases within the same switch statement

I am looking through someone's C code, and discovered something I didn't even know was possible. Inside some of the cases, the switch variable is modified, with the intention that another case is executed after the break.

The switch is inside an interrupt handler, so it will get called repeatedly.

switch (variable)
{
    case 1:
        some_code();
        variable = 3;
        break;

    case 2:
        more_code();
        variable = 5;
        break;

    case 3:
        more_code();
        variable = 5;
        break;

    case 4:
        my_code();
        break;

    case 5:
        final_code();
        break;

}

The code seems to be working as the author intended.

Is this guaranteed behaviour in C? I always assumed that the break statement would cause execution to jump to directly after the switch statement. I wouldn't have expected it to continue testing every other case.

like image 957
Rocketmagnet Avatar asked Mar 24 '23 23:03

Rocketmagnet


1 Answers

This is a common technique for state machine type code. But it doesn't jump automatically like you imagine. The switch statement has to be put inside a while loop. In this case, I imagine the loop would look something like:

while (!done) {
    done = (variable == 5);
    switch (variable) {
    /*...*/
    }
}

Alternatively, the switch statement could be inside a function body, and that function is called from a loop until the done condition is met.

like image 79
jxh Avatar answered Apr 18 '23 06:04

jxh