Running multiple cases within a single switch statement

I was looking at C code and found that something I didn't even know was possible. In some cases, the switch variable is modified with the intention of executing another case after the break.

The switch is inside the interrupt handler, so it will be called again.

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 work as the author intended.

Is this guaranteed behavior in C? I always assumed that the break statement would lead to a jump to execution right after the switch statement. I would not expect this to continue to test any other case.

+4
source share
1 answer

This is a general method for state machine type code. But he does not jump automatically, as you imagine. The switch must be placed inside a while . In this case, I think the loop would look something like this:

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

Alternatively, the switch can be located inside the body of the function, and this function is called from the loop until the condition is satisfied.

+7
source

Source: https://habr.com/ru/post/1480589/


All Articles