break, continue, and Labels
In this page:
Using break
break immediately exits the loop it is inside, skipping any remaining iterations, and execution continues with the code right after the loop.
Example: Using break
fun main() {
for (i in 1..10) {
if (i == 5) break
println("i = $i")
}
println("Loop exited")
}
Login to try C/C++/Java/PHP code in the editor
Using continue
continue skips the rest of the current iteration's body and jumps straight to the next iteration's condition check.
Example: Using continue
fun main() {
for (i in 1..5) {
if (i % 2 == 0) continue
println("Odd number: $i")
}
}
Login to try C/C++/Java/PHP code in the editor
Labeling a Loop
Writing name@ directly before a loop gives it a label, which can then be targeted by break@name or continue@name from inside a nested loop.
Example: Labeling a Loop
fun main() {
outer@ for (i in 1..3) {
for (j in 1..3) {
if (j == 2) continue@outer
println("i=$i, j=$j")
}
}
}
Login to try C/C++/Java/PHP code in the editor
Breaking an Outer Loop
A labeled break@name inside nested loops exits the specifically named outer loop entirely, rather than just the innermost one.
Example: Breaking an Outer Loop
fun main() {
search@ for (i in 1..3) {
for (j in 1..3) {
if (i == 2 && j == 2) break@search
println("Checking i=$i, j=$j")
}
}
println("Search finished")
}
Login to try C/C++/Java/PHP code in the editor
- Assuming a plain
breakinside a nested loop exits all surrounding loops, when it only exits the innermost one unless a label is used. - Forgetting the
@symbol when defining or referencing a label, such as writingloopinstead ofloop@. - Overusing labeled breaks/continues where restructuring the loops or extracting a function would be clearer.
breakexits the nearest enclosing loop immediately;continueskips to the next iteration of it.- A label is written as
name@before a loop, and referenced asbreak@nameorcontinue@name. - Labeled
break/continuelet you control an outer loop from inside a nested one. - Without a label,
break/continueonly affect the innermost loop they are written in.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: