"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 Break Out of a Loop from Within a Switch Statement in C++?

How to Break Out of a Loop from Within a Switch Statement in C++?

Published on 2024-11-13
Browse:123

How to Break Out of a Loop from Within a Switch Statement in C  ?

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:

while(true) {
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        **HERE, break out of the loop itself**
    }
}

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:

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

   }
}
exit_loop: ;

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.

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