How to break out of a loop from inside a switch?
An alternate solution is to use the keyword continue
in combination with break
, i.e.:
for (;;) {
switch(msg->state) {
case MSGTYPE:
// code
continue; // continue with loop
case DONE:
break;
}
break;
}
Use the continue
statement to finish each case label where you want the loop to continue and use the break
statement to finish case labels that should terminate the loop.
Of course this solution only works if there is no additional code to execute after the switch statement.
You can use goto
.
while ( ... ) {
switch( ... ) {
case ...:
goto exit_loop;
}
}
exit_loop: ;