Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a break statement break from a switch/select?

People also ask

Does Break break out of a switch statement?

You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.

What is the difference between switch and break statement?

Break statement causes code execution to come out of the block and execute next statements because of which switch statement will execute only one case statement and exit out of switch block without executing other case blocks.


Break statements, The Go Programming Language Specification.

A "break" statement terminates execution of the innermost "for", "switch" or "select" statement.

BreakStmt = "break" [ Label ] .

If there is a label, it must be that of an enclosing "for", "switch" or "select" statement, and that is the one whose execution terminates (§For statements, §Switch statements, §Select statements).

L:
  for i < n {
      switch i {
      case 5:
          break L
      }
  }

Therefore, the break statement in your example terminates the switch statement, the "innermost" statement.


A hopefully illustrative example:

loop:
for {
        switch expr {
        case foo:
                if condA {
                        doA()
                        break // like 'goto A'
                }

                if condB {
                        doB()
                        break loop // like 'goto B'                        
                }

                doC()
        case bar:
                // ...
        }
A:
        doX()
        // ...
}

B:
doY()
// ....

Yes, break breaks the inner switch.

https://play.golang.org/p/SZdDuVjic4

package main

import "fmt"

func main() {

myloop:
    for x := 0; x < 7; x++ {
        fmt.Printf("%d", x)
        switch {
        case x == 1:
            fmt.Println("start")
        case x == 5:
            fmt.Println("stop")
            break myloop
        case x > 2:
            fmt.Println("crunching..")
            break
        default:
            fmt.Println("idling..")
        }
    }
}
0idling..
1start
2idling..
3crunching..
4crunching..
5stop

Program exited.

Just from a switch block. There's plenty of examples in Golang own code you can examine (compare inner break with outer break).


This question might be too old already but I still think label makes our code become harder to read. Instead of breaking the for inside select, just set a flag for the loop and handle it inside select-case before invoking break. For example:

loop := true
for loop {
    select {
    case <-msg:
        // do your task here
    case <-ctx.Done():
        loop = false
        break
    }
}