8

I have the following code:

int x = 100; //Or some other value

while(x > 0) {

    for(int i = 5; i > 0; i++) {

        x = x-2;

        if(x == 0)
            break;

        }

}

However, this will only break the for loop. How can I have it so that it breaks both the for and the while loops?

Cheers!

1
  • 3
    Considering x is equal to zero when you break, the while condition will also be false ;) Commented Mar 20, 2013 at 14:05

4 Answers 4

6

You can use a labeled break, which redirects the execution to after the block marked by the label:

OUTER:
while(x > 0) {
    for(int i = 5; i > 0; i++) {
        x = x-2;
        if(x == 0)
            break OUTER;
    }
}

Although in that specific case, a simple break would work because if x == 0 the while will exit too.

Sign up to request clarification or add additional context in comments.

4 Comments

Obligatory remark: xkcd.com/292
@akaIDIOT There is a difference between a goto that sends you miles away and exiting a nested loop. The latter is fine I think.
@assylias simple use of labels like this could be considered fine. I personally simply avoid them and look for ways to refactor things slightly to something that itches less (like using return from a separate method that hides the complexity of a bunch of loops away). All in all: to each his own :)
@akaIDIOT I would also try to refactor it to be honest - but I can imagine situations where it is not convenient.
1
bool done=false;
while(!done && x > 0) {
    for(int i = 5;!done &&  i > 0 ; i++) {
        x = x-2;
        if(x == 0){
            done=true;
            break ;
        }
    }
}

Comments

0

See this example

Outer:
    for(int intOuter=0; intOuter < intArray.length ; intOuter++)
    {
      Inner:
      for(int intInner=0; intInner < intArray[intOuter].length; intInner++)
      {
        if(intArray[intOuter][intInner] == 30)
        {
          blnFound = true;
          break Outer;
        }  

      }
    }

Comments

0

Try to avoid breaks, there's always an other way to write your loop so you don't need it which is much 'prettier' and easier to understand if someone else has to modify your code. In your example the while loop is unnecessary but to show you how it's possible:

while(x > 0) {

  for(int i = 5; i > 0 && x!=0; i++) {

    x = x-2;

  }

}

If x equals 0, the for-loop will be left. Then your while condition will be verified: x is smaller then 0 (it's zero) so your while loop will stop executing too.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.