• 12
• 12
• 9
• 10
• 13

# C++ labeled break?

This topic is 4369 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

hi, i'm just wondering if there is an equivalent for this common Java command in C++. How to I break out of an outer level loop? eg. in java:
OuterLoop:
while(true)
{
//random code
while(true)
{
//random code
if(something)
break OuterLoop;
}
}


##### Share on other sites
The infinately abuseable goto command with a label after the loop is about as close as your going to get...

##### Share on other sites
There's no command for this that I know of in C++ but, you can achieve the same thing with something like this:

bool state = true;while ( state != false )     {        while ( true )            if ( blah... )              {               state = false;               break;              }      }

- xeddiex

##### Share on other sites
yes as eddie mentioned.
you can use Flags.

##### Share on other sites
Quote:
 Original post by CuppoJavahi,i'm just wondering if there is an equivalent for this common Java command in C++.How to I break out of an outer level loop?eg. in java:OuterLoop:while(true){ //random code while(true) { //random code if(something) break OuterLoop; }}

or depending on the situation, you can do this:
while(true){  //random code  while(true)  {    //random code    if(something){      break;    }    break;  }}

##### Share on other sites
Quote:
Quote:
 Original post by CuppoJavahi,i'm just wondering if there is an equivalent for this common Java command in C++.How to I break out of an outer level loop?eg. in java:OuterLoop:while(true){ //random code while(true) { //random code if(something) break OuterLoop; }}

or depending on the situation, you can do this:
while(true){  //random code  while(true)  {    //random code    if(something){      break;    }    break;  }}

The second break will never be reached if you break above it.

##### Share on other sites
I didn't realize that was possible in Java. It seems a little strange, too, seeing as how it boasts of being safer than C++. breaks are restricted gotos, as they only take program flow in one directly, directly after the given loop. A labeled break is slightly more dangerous in that the # of loops broken can be greater than 1.

I guess I can add that to one of the few features I like about Java.

##### Share on other sites
Either hoist your inner loops into a separate function and use a return, or use a goto.

Building a scaffolding of flag-based breaks is clumsy.

##### Share on other sites
Yeah, the only suggestion that applied to my situation was the flag check solution.
Unfortunately, this is quite an intricate piece of code with four layers of loops, so flag checking would result in an unreadable mess, so I opted to pull my code into methods, using returns as a break substitute.

Thanks for the ideas guys.