42

I know a break statement jumps out of a loop, but does it jump out of nested loops or just the one its currently in?

nbro
  • 15,395
  • 32
  • 113
  • 196
Craig
  • 421
  • 1
  • 4
  • 3

4 Answers4

85

Without any adornment, break will just break out of the innermost loop. Thus in this code:

while (true) { // A
    while (true) { // B
         break;
    }
}

the break only exits loop B, so the code will loop forever.

However, Java has a feature called "named breaks" in which you can name your loops and then specify which one to break out of. For example:

A: while (true) {
    B: while (true) {
         break A;
    }
}

This code will not loop forever, because the break explicitly leaves loop A.

Fortunately, this same logic works for continue. By default, continue executes the next iteration of the innermost loop containing the continue statement, but it can also be used to jump to outer loop iterations as well by specifying a label of a loop to continue executing.

In languages other than Java, for example, C and C++, this "labeled break" statement does not exist and it's not easy to break out of a multiply nested loop. It can be done using the goto statement, though this is usually frowned upon. For example, here's what a nested break might look like in C, assuming you're willing to ignore Dijkstra's advice and use goto:

while (true) {
    while (true) {
        goto done;
    }
}
done:
   // Rest of the code here.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 15
    Good answer. If you find yourself resorting to named breaks, however, you are quite possibly not doing it "the right way". :-) – Haakon Feb 23 '11 at 21:46
  • 2
    Please for the sake of the people looking at your code, don't used named breaks! – Tazzy531 Feb 23 '11 at 21:50
  • 6
    Named breaks are not that bad, there are situation where they are the best choice. However, using them more often than twice per year is strange. – maaartinus Feb 23 '11 at 22:15
  • 4
    Nothing wrong with named breaks, especially if the alternative is multiple control variables and convoluted conditional logic. – DJClayworth Feb 23 '11 at 22:35
4

By default, it jumps out of the innermost loop. But you can specify labels and make it jump of outer loops too.

biziclop
  • 48,926
  • 12
  • 77
  • 104
0

You can also break out by using Exceptions, so you can handle multiple reasons

 void fkt1() {
    try {
        while (true)
            fkt2();
    } catch (YourAbortException e) {
        e.printStackTrace();
    }

    //go on
}

void fkt2() {
    while (true)
        if (abort)
            throw new YourAbortException();
}
Marian Klühspies
  • 15,824
  • 16
  • 93
  • 136
-2

it breaks 1 loop . very simple. for ex:

for loop
   for loop
      break;
   end for loop
end for loop

break out of inner loop but still in outer loop

DanielBarbarian
  • 5,093
  • 12
  • 35
  • 44
minh nguyen
  • 89
  • 3
  • 3