Keywords: switch | continue | loop | C | C++
Abstract: This article explores the behavior of using the continue statement inside a switch statement in C and C++ programming languages. Through code examples and theoretical analysis it explains how continue is ignored by the switch and applied to the enclosing loop and provides equivalent alternatives to enhance code clarity.
In programming particularly in C and C++ languages switch statements and loop control structures are common. A common question is whether the continue statement can be used inside a switch to jump to the next iteration of the outer loop. This article explores the legitimacy of this behavior through code examples and theoretical analysis.
Interaction Between continue and switch Statements
According to the C language standard the continue statement is only applicable to loop structures such as while for or do-while. When continue appears inside a switch statement it is ignored by the switch and applied to the enclosing loop.
while (something = get_something()) {
switch (something) {
case A:
case B:
break;
default:
continue;
}
do_something();
}
As shown in the code when something is not A or B the continue statement executes causing the loop condition to be retested and skipping do_something().
Equivalent Code and Alternative Implementations
Code can be refactored to avoid using continue inside a switch. For example using an if statement
while (something = get_something()) {
if (something == A || something == B)
do_something();
}
Alternatively if it is necessary to ensure the loop continues until a condition is met a do-while loop can be used
do {
something = get_something();
} while (!(something == A || something == B));
do_something();
These alternative structures are clearer and avoid complex control flow.
Conclusion
Using continue in a switch statement is legitimate but should be used cautiously to ensure code readability. In C and C++ the behavior is consistent but best practices prioritize simple control structures.