Go

How does switch differ from C, and what does this fallthrough example print?

Question 24MediumGo 1.22 to 1.25
switch x := 2; x {
case 1:
	fmt.Println("one")
case 2:
	fmt.Println("two")
	fallthrough
case 3:
	fmt.Println("three")
	fallthrough
case 100:
	fmt.Println("hundred")
default:
	fmt.Println("default")
}

Output: two, three, hundred (each on its own line).

Go cases don't fall through by default. After a matching case finishes, the switch ends. fallthrough moves control to the first statement of the next case without checking that case's condition. That is why case 100 runs even though x is 2. Execution stops at hundred because that case has no fallthrough, so default never runs.

Rules and differences from C:

  • fallthrough must be the last statement in a case. It can't be used in the final case or in a type switch.
  • Cases can list several values (case 'a', 'e', 'i':), and those values don't have to be constants.
  • Duplicate constant cases are a compile error.
  • A switch with no expression means switch true, which is a clean way to write if/else chains. Cases are checked from top to bottom and stop at the first match.
  • default can appear anywhere in the list. It is still used only when no other case matches.

More on Language Fundamentals & Types

All 39 Language Fundamentals & Types questions