Go

What do these two loops print when the body changes the loop variable?

Question 479HardGo 1.22 to 1.25
for i := 0; i < 5; i++ {
    i++
    fmt.Print(i, " ")
}
fmt.Println()
for i := range 5 {
    i++
    fmt.Print(i, " ")
}

The first prints 1 3 5. The second prints 1 2 3 4 5.

In a three-clause loop, Go 1.22 still makes a new variable for each iteration, but it copies the value from the end of the previous iteration before it runs the post statement. A change made in the body therefore carries into the next iteration, just as it did before 1.22.

In range 5 (range over int, Go 1.22), the iteration values 0..4 come from the range itself. Assigning to i changes only that iteration's copy, so the next iteration still gets the next value. The same applies to for i := range slice. This checks whether you know that per-iteration scoping is not the same as "the variable cannot be changed".

More on Tricky Output & Code-Review Puzzles

All 38 Tricky Output & Code-Review Puzzles questions