"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to jump out of a loop from a Switch statement in C++?

How to jump out of a loop from a Switch statement in C++?

Posted on 2025-04-15
Browse:322

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:

while ( ... ) {
   switch( ... ) {
     case ...:
         goto exit_loop;

   }
}
exit_loop: ;

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:

bool should_exit = false;

while ( ... ) {
   switch( ... ) {
     case ...:
         should_exit = true;
         break;
     // ... more stuff ...
     case DONE:
         should_exit = true;
         break;
   }

   if (should_exit) {
       break;
   }
}

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3