W3Basic Logo

Go break and continue

The break statement is used to terminate the for and while loops whereas the continue statement are used to skip the rest of the current iteration of the loop and go to the next one.


break and continue

Let's continue exploring more advanced instructions to control the flow of the program. Both break and continue can be seen as special cases of goto while dealing with for loops.

The break instruction

The break instruction is used to exit a loop without executing neither the rest of the current iteration nor the next ones.

package main

import "fmt"

func main() {
	for i := 1; i <= 10; i++ {
		if i == 5 {
			break
		}
		fmt.Println(i)
	}

}
1
2
3
4

This will print 1, 2, 3, 4 and then exit the loop.

A more useful example of break is the following:

func findNumber(numbers []int, n int) bool {
    int index := -1
    for i, number := range numbers {
        if number == n {
            index = i
            break
        }
    }
    return index
}

As soon as we find the number we are looking for, we exit the loop and return the index of the number. Without break, the function would have returned the index of the last occurrence of the number.

The continue instruction

The continue instruction is used to skip the rest of the current iteration of the loop and go to the next one.

for i := 1; i <= 10; i++ {
    if i == 5 {
        continue
    }
    fmt.Println(i)
}

This will print 1, 2, 3, 4, 6, 7, 8, 9, 10.

This is useful when we want to avoid some special cases in the loop, for example, when we want to avoid dividing by zero:

func printInverses(numbers []int) {
    for _, number := range numbers {
        if number == 0 {
            continue
        }
        fmt.Println(1 / number)
    }
}

A word of caution

As for goto, break and continue are powerful but interrupt the flow of the program in a way that is not always easy to follow. Before using them, make sure that you really need them and that you can't find a simpler solution.

© 2023 W3Basic. All rights reserved.

Follow Us: