Home >Backend Development >C++ >How to Exit a Loop from Within a Switch Statement in C : Using `goto` or a Flag?
Alternative Approaches to Exiting a Loop from Within a Switch
In certain scenarios, one may encounter the need to terminate an enclosing loop from within a switch statement. While using a flag is a common approach, C provides an alternative solution: using the goto statement.
The Dilemma:
Consider the following code snippet:
<code class="cpp">while(true) { switch(msg->state) { case MSGTYPE: // ... break; // ... more stuff ... case DONE: // **HERE, I want to break out of the loop itself** } }</code>
The goal is to exit the loop immediately when the msg->state equals DONE.
Using goto:
C allows the use of the goto statement to explicitly jump to a specific location in the code. This can be leveraged to achieve the desired behavior:
<code class="cpp">while ( ... ) { switch( ... ) { case ...: goto exit_loop; // Jump to this location when msg->state is DONE } } exit_loop: ; // Label for jump target</code>
In this modified code, when msg->state equals DONE, the goto statement directs the execution flow to the exit_loop label. This consequently exits both the switch and the enclosing loop.
Note: It's important to use labels (:) to identify the target of the goto statement. Using goto indiscriminately can lead to spaghetti code and maintainability issues.
The above is the detailed content of How to Exit a Loop from Within a Switch Statement in C : Using `goto` or a Flag?. For more information, please follow other related articles on the PHP Chinese website!