-3

In below piece of code, I am unable to understand why the break statement in default is not sufficient to end infinite loop. PlayGroundLink

package main

import "fmt"

func main() {
    for { //infinite loop
        fmt.Print("Enter Choice")
        userChoice := 3 //Intenssionaly given value here for testing
        switch userChoice {
        case 1:
            fmt.Println("Enter Radios of Circle:")
        case 2:
            fmt.Println("Enter Radios of Circle:")
        default:
            fmt.Println("\nExiting...")
            break  // this break is executing , but why it is not coming out of infinte 'for' loop ?
        }

    }
}

OutPut of above Code (Not Ending .. keep on going )

Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Arun
  • 1,651
  • 4
  • 20
  • 31

1 Answers1

2

If you add a label to your loop, you can explicitly break from the loop:

package main

import "fmt"

func main() {
    Loop:
        for { //infinite loop
            fmt.Print("Enter Choice")
            userChoice := 3 //Intenssionaly given value here for testing
            switch userChoice {
            case 1:
                fmt.Println("Enter Radios of Circle:")
            case 2:
                fmt.Println("Enter Radios of Circle:")
            default:
                fmt.Println("\nExiting...")
                break Loop
            }

        }
    fmt.Println("Outside the loop!")
}

Here's a working example

TayTay
  • 6,882
  • 4
  • 44
  • 65