Stop and skip with break and continue
Stop and skip with break and continue
Use break to exit the innermost enclosing for, switch or select. Use continue to skip the remainder of the current iteration of the innermost loop. In a three-part for, continue still reaches the post statement before the next condition check.
package main
import "fmt"
func main() { for i := 1; i <= 5; i++ { if i == 3 { break } fmt.Println(i) }}When i becomes 3, break exits the loop before the print. Execution resumes after the loop, not at the next iteration.
Skip only one iteration
package main
import "fmt"
func main() { for i := 1; i <= 5; i++ { if i%2 == 0 { continue } fmt.Println(i) }}The remainder operator detects even values. Continue skips printing them but the loop advances through i++. In a condition-only loop, placing continue before the state update can accidentally prevent progress; make sure the state is updated on every continuing path.
Try it locally
Loop from 1 through 8. Skip 2 and stop before printing 6. Expected lines: 1, 3, 4, 5.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Loops 03: Stop and skip with break and continue
Check the lesson objective before moving on.
Which statement exits the loop entirely?
Does continue skip i++ in a three-part for?