Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

In Java, how does break interact with nested loops?

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?

question from:https://stackoverflow.com/questions/5097513/in-java-how-does-break-interact-with-nested-loops

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...