Breaking Out of Loops from Within Switches
In C , it is sometimes necessary to break out of a loop from within a switch statement. In the code snippet provided, the user wants to exit the loop when the state of the message is set to DONE.
Using goto Statement
The most straightforward way to achieve this is by using the goto statement, as demonstrated in the code below:
<code class="c++">while ( ... ) { switch( ... ) { case ...: goto exit_loop; } } exit_loop: ;</code>
In this example, the goto statement jumps to the label exit_loop when the state is set to DONE, effectively breaking out of both the switch statement and the while loop.
Using a Flag Variable
An alternative approach is to use a flag variable. This can be a boolean variable that is set to true when the desired condition is met within the switch statement. The loop can then be broken by checking the flag variable after the switch statement.
Here's an example:
<code class="c++">bool should_exit = false; while ( ... ) { switch( ... ) { case ...: should_exit = true; break; // ... more stuff ... case DONE: should_exit = true; break; } if (should_exit) { break; } }</code>
In this case, the should_exit flag is set to true when the state is set to DONE, and the loop is broken when the flag is checked after the switch statement.
The above is the detailed content of How to Break Out of Loops from Within Switch Statements in C ?. For more information, please follow other related articles on the PHP Chinese website!