Home > Backend Development > C++ > How to Break Out of Loops from Within Switch Statements in C ?

How to Break Out of Loops from Within Switch Statements in C ?

Mary-Kate Olsen
Release: 2024-10-30 03:35:28
Original
551 people have browsed it

How to Break Out of Loops from Within Switch Statements in C  ?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template