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!

MrD
  • 4,986
  • 11
  • 48
  • 90

4 Answers4

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • 5
    Obligatory remark: http://xkcd.com/292/ – akaIDIOT Mar 20 '13 at 14:04
  • @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 Mar 20 '13 at 14:24
  • @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 Mar 20 '13 at 14:29
  • @akaIDIOT I would also try to refactor it to be honest - but I can imagine situations where it is not convenient. – assylias Mar 20 '13 at 14:37
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 ;
        }
    }
}
Luca Rocchi
  • 6,272
  • 1
  • 23
  • 23
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;
        }  

      }
    }
Apurv
  • 3,723
  • 3
  • 30
  • 51
cowls
  • 24,013
  • 8
  • 48
  • 78
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.

Jonathan Kortleven
  • 613
  • 1
  • 5
  • 16