patterngoCritical
Does a break statement break from a switch/select?
Viewed 0 times
fromstatementdoesbreakswitchselect
Problem
I know that
Does the
switch/select statements break automatically after every case. I am wondering, in the following code:for {
switch sometest() {
case 0:
dosomething()
case 1:
break
default:
dosomethingelse()
}
}Does the
break statement exit the for loop or just the switch block?Solution
Break statements, The Go Programming Language Specification.
A "break" statement terminates execution of the innermost "for",
"switch" or "select" statement.
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).
Therefore, the
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.Code Snippets
BreakStmt = "break" [ Label ] .L:
for i < n {
switch i {
case 5:
break L
}
}Context
Stack Overflow Q#11104085, score: 301
Revisions (0)
No revisions yet.