educative.io

Clarification of Out put for goto classes

package main
import “fmt”

func main() {
LABEL1: // adding a label for location
for i := 0; i <= 5; i++ { // outer loop
for j := 0; j <= 5; j++ { // inner loop
if j == 4 {
continue LABEL1 // jump to the label
}
fmt.Printf(“i is: %d, and j is: %d\n”, i, j)
}
}
}

This should give infinity loop right since i value is being reinitialized with 0 but why i is not getting reinitialized ?


Course: https://www.educative.io/collection/10370001/6289391964127232
Lesson: https://www.educative.io/collection/page/10370001/6289391964127232/4540774379159552

Hi @Afrid,

The provided code will not result in an infinite loop. The reason is that the i variable is not being reinitialized to 0 on each iteration of the inner loop due to the placement of the LABEL1 label.

In Go, when a continue statement is encountered with a label, it will jump to the labeled statement, but it won’t reinitialize the loop variables. In this case, it continues with the next iteration of the outer loop without resetting the i variable.

Let’s break down the code:

package main

import "fmt"

func main() {
LABEL1: // adding a label for location
	for i := 0; i <= 5; i++ { // outer loop
		for j := 0; j <= 5; j++ { // inner loop
			if j == 4 {
				continue LABEL1 // jump to the label
			}
			fmt.Printf("i is: %d, and j is: %d\n", i, j)
		}
	}
}

Here’s what happens:

  • The outer loop (for i := 0; i <= 5; i++) runs from 0 to 5.
  • The inner loop (for j := 0; j <= 5; j++) runs from 0 to 5 for each iteration of the outer loop.
  • When j becomes 4, the continue LABEL1 statement is executed, which jumps to the LABEL1 label, effectively skipping the rest of the inner loop.
  • However, the outer loop continues with the next iteration, and the value of i is not reinitialized to 0.

As a result, you will see output for i and j where j skips printing when it’s equal to 4, but the outer loop continues with the next value of i. The output will be:

i is: 0, and j is: 0
i is: 0, and j is: 1
i is: 0, and j is: 2
i is: 0, and j is: 3
i is: 1, and j is: 0
i is: 1, and j is: 1
i is: 1, and j is: 2
i is: 1, and j is: 3
i is: 2, and j is: 0
i is: 2, and j is: 1
i is: 2, and j is: 2
i is: 2, and j is: 3
i is: 3, and j is: 0
i is: 3, and j is: 1
i is: 3, and j is: 2
i is: 3, and j is: 3
i is: 4, and j is: 0
i is: 4, and j is: 1
i is: 4, and j is: 2
i is: 4, and j is: 3
i is: 5, and j is: 0
i is: 5, and j is: 1
i is: 5, and j is: 2
i is: 5, and j is: 3

You’ll notice that the value of i continues to increment as the outer loop progresses.