Breaking Out of Loops from Within a Switch Statement
While navigating through code, situations may arise where you need to exit a loop from within a switch statement. Consider the following scenario:
<code class="cpp">while(true) { switch(msg->state) { case MSGTYPE: // ... break; // ... more stuff ... case DONE: **HERE, break out of the loop itself** } }</code>
The goal is to find an elegant way to break out of the enclosing loop without resorting to flags or conditional breaks.
A Swift Exit: Using 'goto'
In the realm of C , the 'goto' statement provides a straightforward solution. It allows you to jump to a specific label within the current function. By leveraging 'goto,' you can cleanly exit the loop from within the switch statement:
<code class="cpp">while ( ... ) { switch( ... ) { case ...: goto exit_loop; } } exit_loop: ;</code>
This approach offers a concise and explicit way to terminate the loop. Keep in mind that 'goto' should be used sparingly to maintain code readability. However, in certain situations, it can provide a simple and effective solution.
The above is the detailed content of How to Break Out of a Loop from Within a Switch Statement in C ?. For more information, please follow other related articles on the PHP Chinese website!