Leaving a loop or skipping a round

A loop checks its condition once per round. Sometimes you find out in the middle of the body that you want to stop, or that this round is not needed. Two statements help here:

  • break ends the whole loop right away.
  • continue ends only the current round. The loop goes on with the next round.
package main

import "fmt"

func main() {
	for i := 1; i <= 10; i++ {
		if i%2 == 1 {
			continue
		}
		if i == 8 {
			break
		}
		fmt.Println(i)
	}
	fmt.Println("Loop ended")
}

Output:

2
4
6
Loop ended

Follow the rounds one by one:

iWhat happens
1, 3, 5, 7odd, so continue: nothing printed
2, 4, 6even and not 8: printed
8break: the loop ends

The loop was set up for 10 rounds, but 9 and 10 never ran. After break, Go goes straight to the first line after the loop. In a three-part for, continue still runs the step i++ before the next round, so the counter keeps moving.

A way out of for { }

The last lesson showed for { }, a loop with no condition that never stops on its own. break gives it an exit. This is useful when you only know it is time to stop after you have read a value. Here the program adds up numbers until it reads a 0. The input is 4, -2, 6, 0 and 9:

sum := 0
for {
	var n int
	fmt.Scan(&n)
	if n == 0 {
		break
	}
	if n < 0 {
		continue
	}
	sum += n
}
fmt.Println("Sum:", sum)

Output:

Sum: 10

The -2 was skipped by continue, so the sum is 4 + 6. When the program read the 0, break ended the loop. The 9 was never read.

A value like this 0, which means "the input is over", is often called a sentinel. It lets the user enter as many values as they like.

break inside a switch

In Go, break also works inside a switch, and there it ends only the switch, not the loop around it. This surprises many people:

for i := 1; i <= 5; i++ {
	switch i {
	case 3:
		fmt.Println("Trying to stop")
		break
	}
	fmt.Println(i)
}

Output:

1
2
Trying to stop
3
4
5

The break left the switch, and the loop went on to 4 and 5. When you need to leave a loop from inside a switch, use an if for that check instead, as the earlier examples do. The Nested Loops lesson shows one more way, a labeled break.

Use break and continue where they make a loop easier to follow, for example to skip bad values at the top of the body. A loop with many exits is hard to read, because you have to find every one of them to know what it does.

In the exercise, read order totals until a 0, skip the negative ones with continue, stop at the 0 with break, and print how many totals were counted and their sum.