Reason about loop termination and goto
Reason about loop termination and goto
A terminating loop has a reachable exit. For simple countdowns, identify a nonnegative quantity that decreases on every continuing path. A condition-free for loop can stop with break. Go also has goto, which transfers control to a label in the same function; prefer structured loops for ordinary repetition.
package main
import "fmt"
func main() { remaining := 3 for { if remaining == 0 { break } fmt.Println(remaining) remaining-- } fmt.Println("done")}The exit is checked before each decrement. Starting at three, the nonnegative remaining value decreases until it reaches zero. If the starting value were negative, this equality guard would not give the intended countdown; validate the initial state or use a positive-state condition.
A bounded goto example
package main
import "fmt"
func main() { attempt := 0Retry: attempt++ fmt.Println(attempt) if attempt < 2 { goto Retry }}The label is before the increment, so the second visit increases attempt to 2 and the branch is no longer taken. A goto cannot jump into a block from outside it or introduce variables into scope that were not in scope at the jump. Avoid goto when a for loop communicates the same intent more clearly.
Try it locally
Rewrite the bounded goto example as a three-part for loop without goto. Print 1 and 2 on separate lines.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Loops 07: Reason about loop termination and goto
Check the lesson objective before moving on.
Which fact supports termination of the first program?
Where can goto jump?