How to break out of a loop from inside a switch?

jrharshath picture jrharshath · Sep 14, 2009 · Viewed 110.6k times · Source

I'm writing some code that looks like this:

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

Is there any direct way to do that?

I know I can use a flag, and break from the loop by putting a conditional break just after the switch. I just want to know if C++ has some construct for this already.

Answer

Mehrdad Afshari picture Mehrdad Afshari · Sep 14, 2009

You can use goto.

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

   }
}
exit_loop: ;