Programming Search⌘K

Conceptcore

Switch statement

Also called switch, switch statement, case statement, multiway branch, multi-way branch, select case, switch expression, case labels, default label, when expression.

A switch statement compares one value with a list of case labels and jumps to the code of the label that matches, or to a default label when no label matches.

Applies to
core-languages

Idea

A program often has to choose one of many paths by the value of one thing: a menu choice, a command letter, a kind of token. A chain of if and else if can do it, but the chain repeats the value in each test, and a reader must check each test to see that they all compare the same value. A switch statement names the value once and lists the cases. Wikipedia describes it as "a selection control flow mechanism that changes execution control based on the value of an expression"1, and adds that "instead of branching only on true or false, it branches on any number of values"1.

#include <stdio.h>

int main(void) {
    const char *text = "a cat, 2 dogs";
    int vowels = 0, spaces = 0, punctuation = 0, other = 0;
    for (const char *p = text; *p != '\0'; p++) {
        switch (*p) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            vowels++;
            break;
        case ' ':
            spaces++;
            break;
        case ',':
        case '.':
            punctuation++;
            break;
        default:
            other++;
            break;
        }
    }
    printf("vowels %d, spaces %d, punctuation %d, other %d\n", vowels, spaces, punctuation, other);
    return 0;
}
Output
vowels 3, spaces 3, punctuation 1, other 6

The value *p is written once. Each case label is a constant, and five labels share the code that counts a vowel. The default label takes each character that no label names. Each group of statements ends with break, which leaves the switch. Without the break, C goes on into the code of the next label. That rule is the subject of Fall-through.

How it works

The value and the labels. The value that a switch tests has different names: the controlling expression in C, the selector expression in Java. In C, "The controlling expression of a switch statement shall have integer type", and "The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion"2. Other languages accept more types. In Java, "The type of the selector expression must be char , byte , short , int , or a reference type, or a compile-time error occurs"3, so a Java switch can test a String or an enum. In C++, the condition can have an integral type, an enumeration type or a class type that converts to one of them4. In Go, the case expressions "need not be constants"5.

The jump. A C switch is a computed jump. "If a converted value matches that of the promoted controlling expression, control jumps to the statement following the matched case label. Otherwise, if there is a default label, control jumps to the labeled statement. If no converted case constant expression matches and there is no default label, no part of the switch body is executed"2. Most languages keep this rule for the default label. In Go, the case expressions "are evaluated left-to-right and top-to-bottom; the first one that equals the switch expression triggers execution of the statements of the associated case; the other cases are skipped"5. JavaScript compares "using the strict equality comparison"6.

The end of a case. In C, C++, Java and JavaScript, a case is only a label in a block of statements. Java states the rule for a group of statements: "all the block statements in the switch block that follow the switch label are executed, including those that appear after subsequent switch labels"3. A break ends the switch. Other languages end each case by themselves. In Go, control goes to the end of the switch after a case, unless the last statement of the case is fallthrough5. In C#, "Falling through from one switch section to the next generates a compiler error"7. In Bash, a case that ends with ;; stops after the first match, and ;& and ;;& continue8. Fall-through compares these rules.

Several values for one case. A case often stands for several values. C and Java put several labels in front of one group of statements, and in Java "Multiple switch labels are permitted for a switch labeled statement group"3. Go lists the values in one case, as in case 0, 1, 2, 3:5. Kotlin separates them with commas9, and Python joins them with |10.

Switch expressions. A switch statement runs code. A switch expression gives a value. Java 14 extended switch "so it can be used as either a statement or an expression"11, with the new labels case ... -> that have no fall-through. "When a switch label applies, and that switch label is for a switch rule, the switch rule expression or statement introduced by the switch label is executed, and nothing else"3. C# 8.0 added switch expressions12. Kotlin when "evaluates its argument and compares the result against each branch in order until one branch condition is satisfied", and it can be an expression or a statement9. SQL has the CASE expression, "a generic conditional expression, similar to if/else statements in other programming languages"13.

Switch and match. Rust match and Python match look like a switch, but they compare the value with patterns, not only with constants. The Python tutorial says that match is "superficially similar to a switch statement in C, Java or JavaScript (and many other languages), but it’s more similar to pattern matching in languages like Rust or Haskell"10. A Rust match must cover each possible value: "The arms’ patterns must cover all possibilities"14. Pattern matching describes the patterns.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeWhen with a subject compares the value with each branch in order, a branch can list several values with commas, and else takes the other values; when can be a statement or an expression. No example file exists because kotlinc is not installed.
SQLNativeThe CASE expression chooses a result with WHEN, THEN and ELSE, either by conditions or by comparison of one value with a list of values. No example file exists.
BashNative
PowerShellNativeSwitch converts each value to a string, and it runs the action of each condition that matches, unless break stops it; -Wildcard and -Regex change the comparison. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no values to branch on.
CSSDoes not applyCSS has no multiway branch on a value; @media and @supports apply rules when a condition is true.
Regular expressionsDoes not applyA regular expression has alternation with |, but it has no branch on the value of an expression.
Language Verdict Form
Python native match with literal patterns and |; the first case that matches runs10
JavaScript native switch with case and default; strict equality; fall-through without break6
TypeScript native the switch of JavaScript; a switch on a literal field narrows a union type15
Java native switch statement and expression; case ... : falls through, case ... -> does not3
Kotlin native when with a subject, branches with commas, and else9
C# native switch statement with no fall-through, and a switch expression7
Go native switch with any comparable value; no fall-through without fallthrough5
Rust native match, which must be exhaustive14
C native switch on an integer with constant labels; fall-through without break2
C++ native the switch of C, also on an enumeration or a class that converts4
Bash native case with glob patterns; ;;, ;& and ;;&8
PowerShell native switch, which runs the action of each condition that matches16
SQL native the CASE expression13
Regex n/a a regular expression has alternation, not a branch on a value
HTML/CSS n/a no values to branch on

The example files sort the same kinds of input in each language. The C, C++, Java and JavaScript examples group labels and end each group with break. The Go example has a switch with no value, which works like an if chain. The C# and Java examples also use a switch expression. The Rust and Python examples use match on literal values. The Bash example uses glob patterns.

PythonGitHub
def days_in(month):
    match month:
        case 2:
            return 28
        case 4 | 6 | 9 | 11:
            return 30
        case _:
            return 31


def http_text(status):
    match status:
        case 200:
            return "OK"
        case 401 | 403:
            return "not allowed"
        case 404:
            return "not found"
        case _:
            return "other"


print(days_in(2), days_in(4), days_in(7))
print([http_text(s) for s in (200, 403, 404, 500)])
Output
28 30 31
['OK', 'not allowed', 'not found', 'other']
  • Verdict: native. Python has no switch. A match with literal patterns does the same job, | joins several values, and case _: takes each other value. Only the first case that matches runs. A bare name in a case is a capture pattern that matches each value, so use literals or dotted names.
#include <iostream>
#include <string_view>

enum class Light { Red, Yellow, Green };

std::string_view advice(Light light) {
    switch (light) {
    case Light::Red:
        return "stop";
    case Light::Yellow:
        return "slow down";
    case Light::Green:
        return "go";
    }
    return "broken light";
}

int main() {
    for (Light light : {Light::Red, Light::Yellow, Light::Green}) {
        std::cout << advice(light) << '\n';
    }

    // A case with a declaration needs its own block.
    int n = 2;
    switch (n) {
    case 1: {
        int doubled = n * 2;
        std::cout << doubled << '\n';
        break;
    }
    case 2:
        std::cout << "two\n";
        break;
    default:
        std::cout << "other\n";
        break;
    }
}
Output
stop
slow down
go
two
  • Verdict: native. A C++ switch can test an enumeration, here an enum class. The function has one case for each enumerator and no default, and the return after the switch handles a value outside the enumerators. In the second switch, the braces give doubled its own block, so the jump to case 2 does not enter its scope.
JavaGitHub
public class Main {
    // The old form: labels with a colon, and break at the end of each group.
    static int daysIn(int month) {
        int days;
        switch (month) {
            case 2:
                days = 28;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                days = 30;
                break;
            default:
                days = 31;
                break;
        }
        return days;
    }

    // The new form: a switch expression with arrows and no fall-through.
    static String kind(String day) {
        return switch (day) {
            case "sat", "sun" -> "weekend";
            case "mon", "tue", "wed", "thu", "fri" -> "weekday";
            default -> "not a day";
        };
    }

    public static void main(String[] args) {
        System.out.println(daysIn(2) + " " + daysIn(4) + " " + daysIn(7));
        for (String day : new String[] {"sat", "wed", "xyz"}) {
            System.out.println(day + " " + kind(day));
        }
    }
}
Output
28 30 31
sat weekend
wed weekday
xyz not a day
  • Verdict: native. daysIn uses the statement form with case ... : labels. Four labels share the group for 30 days, and each group ends with break. kind uses a switch expression on a String. Each case ... -> lists several values, runs only its own code, and gives the value of the expression.
#include <stdio.h>

static const char *action(char command) {
    switch (command) {
    case 'q':
    case 'x':
        return "quit";
    case 'h':
    case '?':
        return "help";
    case 's':
        return "save";
    default:
        return "unknown";
    }
}

int main(void) {
    const char commands[] = "qhs?z";
    for (int i = 0; commands[i] != '\0'; i++) {
        printf("%c: %s\n", commands[i], action(commands[i]));
    }

    // With no default, a value that matches no label runs nothing.
    int n = 7;
    switch (n) {
    case 1:
        printf("one\n");
        break;
    }
    printf("after the switch\n");
    return 0;
}
Output
q: quit
h: help
s: save
?: help
z: unknown
after the switch
  • Verdict: native. A C switch tests an integer, and a char is an integer, so the labels are character constants. Two labels in front of one statement share it. Each case ends with return, so no case runs into the next one. The second switch has no default, so the value 7 runs no part of its body.
using System;

static string Action(char command)
{
    switch (command)
    {
        case 'q':
        case 'x':
            return "quit";
        case 'h':
            return "help";
        default:
            return "unknown";
    }
}

static string Kind(int day) => day switch
{
    6 or 7 => "weekend",
    >= 1 and <= 5 => "weekday",
    _ => "not a day",
};

foreach (var c in "qhz")
{
    Console.WriteLine($"{c}: {Action(c)}");
}
foreach (var day in new[] { 1, 7, 9 })
{
    Console.WriteLine($"{day}: {Kind(day)}");
}
Output
q: quit
h: help
z: unknown
1: weekday
7: weekend
9: not a day
  • Verdict: native. A C# switch statement allows several labels on one section, but a section cannot fall through into the next one, so each section ends with return or break. Kind is a switch expression. Its arms use the patterns 6 or 7 and >= 1 and <= 5, and _ takes each other value.
JavaScriptGitHub
function kind(fruit) {
  switch (fruit) {
    case "apple":
    case "pear":
      return "pome";
    case "cherry":
    case "plum":
      return "stone fruit";
    default:
      return "other";
  }
}

for (const fruit of ["pear", "plum", "kiwi"]) {
  console.log(fruit, kind(fruit));
}

// switch (true) tests conditions, like an if chain.
function size(n) {
  switch (true) {
    case n < 10:
      return "small";
    case n < 100:
      return "medium";
    default:
      return "large";
  }
}

console.log(size(5), size(50), size(500));
Output
pear pome
plum stone fruit
kiwi other
small medium large
  • Verdict: native. A JavaScript switch can test a string, and two labels in a row share one group. Each case ends with return. switch (true) compares true with each case expression in order, so it works like an if chain.
TypeScriptGitHub
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number }
  | { kind: "rectangle"; width: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      // Here shape has the type { kind: "circle"; radius: number }.
      return Math.round(Math.PI * shape.radius ** 2);
    case "square":
      return shape.side ** 2;
    case "rectangle":
      return shape.width * shape.height;
  }
}

const shapes: Shape[] = [
  { kind: "circle", radius: 2 },
  { kind: "square", side: 3 },
  { kind: "rectangle", width: 2, height: 5 },
];
for (const shape of shapes) {
  console.log(shape.kind, area(shape));
}
Output
circle 13
square 9
rectangle 10
  • Verdict: native. TypeScript has the switch of JavaScript. In each case, the compiler narrows shape to the member of the union whose kind is that string, so shape.radius is allowed only in the case for "circle". The three cases cover the union, so the compiler accepts the function with no return after the switch.
package main

import "fmt"

func daysIn(month int) int {
	switch month {
	case 2:
		return 28
	case 4, 6, 9, 11:
		return 30
	default:
		return 31
	}
}

func size(n int) string {
	// A switch with no expression tests each case as a condition.
	switch {
	case n < 10:
		return "small"
	case n < 100:
		return "medium"
	default:
		return "large"
	}
}

func main() {
	fmt.Println(daysIn(2), daysIn(4), daysIn(7))
	fmt.Println(size(5), size(50), size(500))

	// A case ends by itself; there is no break.
	switch x := 1; x {
	case 1:
		fmt.Println("one")
	case 2:
		fmt.Println("two")
	}
}
Output
28 30 31
small medium large
one
  • Verdict: native. A Go case lists several values with commas, as in case 4, 6, 9, 11:. A case ends by itself, so the switch on x prints only one. A switch with no expression compares each case with true, so it works like an if chain. A switch can start with a short statement, such as x := 1.
RustGitHub
fn days_in(month: u32) -> u32 {
    match month {
        2 => 28,
        4 | 6 | 9 | 11 => 30,
        _ => 31,
    }
}

fn size(n: u32) -> &'static str {
    match n {
        0..=9 => "small",
        10..=99 => "medium",
        _ => "large",
    }
}

fn main() {
    println!("{} {} {}", days_in(2), days_in(4), days_in(7));
    println!("{} {} {}", size(5), size(50), size(500));
}
Output
28 30 31
small medium large
  • Verdict: native. Rust has no switch. A match on literal values does the same job, with | for several values and 0..=9 for a range. A match must cover every value of its type, so each match here ends with _.
BashGitHub
kind() {
  case $1 in
    *.jpg | *.png | *.gif)
      echo "image"
      ;;
    *.txt | *.md)
      echo "text"
      ;;
    "")
      echo "no name"
      ;;
    *)
      echo "other"
      ;;
  esac
}

for name in photo.png notes.md run.sh ""; do
  echo "'$name' $(kind "$name")"
done
Output
'photo.png' image
'notes.md' text
'run.sh' other
'' no name
  • Verdict: native. A Bash case matches a word against glob patterns, and | joins several patterns. Each clause ends with ;;, so case stops after the first match. The last pattern, *, matches each word, so it does the job of default.
  • The if chain. A switch with no value, in Go and Kotlin, is a chain of conditions. In Go, "A missing switch expression is equivalent to the boolean value true"5. See Conditional.
  • Lookup tables. A map from keys to values or to functions can replace a switch whose cases only choose a value.
  • Pattern matching. match in Rust and Python, switch with patterns in Java and C#, and when in Kotlin test the shape of a value and bind its parts. See Pattern matching.
  • Fall-through. The cases of a C switch run into each other unless a break stops them. See Fall-through.
  • The task. Write a switch or match writes the same switch in ten languages.

Pitfalls

A missing break

In C, C++, Java and JavaScript, a case without break runs on into the next case. Here the case for "tea" has no break:

This code runs but gives a wrong answer on purpose.

function price(drink) {
  let cents = 0;
  switch (drink) {
    case "tea":
      cents = 200;
    case "coffee":
      cents = 250;
      break;
    default:
      cents = -1;
  }
  return cents;
}

console.log(price("tea"), price("coffee"), price("milk"));
Output
250 250 -1

Tea costs 250, not 200, because the code of the coffee case runs after the code of the tea case. Wikipedia calls the omission of break "a common mistake"1. The fix is a break at the end of each case, or a form with no fall-through, such as case ... -> in Java3. Fall-through shows the compiler warnings that find it.

Strict comparison in JavaScript

A JavaScript switch compares "using the strict equality comparison"6, so the string "2" does not match case 2. A value read from a form or a URL is a string:

This code runs but gives a wrong answer on purpose.

function size(n) {
  switch (n) {
    case 1:
      return "small";
    case 2:
      return "medium";
    default:
      return "unknown";
  }
}

console.log(size(2), size("2"));
Output
medium unknown

Convert the value first, for example with Number(n), or write the cases as strings.

A name that is not a constant in Python

A Python case with a bare name is a capture pattern, not a comparison. "A capture pattern binds the subject value to a name", and "Capture patterns always succeed"17. So case QUIT: matches each value:

This code runs but gives a wrong answer on purpose.

QUIT = "q"


def handle(key):
    match key:
        case "h":
            return "help"
        case QUIT:
            return "quit"


for key in ["h", "q", "x"]:
    print(key, handle(key))
Output
h help
q quit
x quit

The key x gives quit. A dotted name, such as Keys.QUIT, is a value pattern, and it "will succeed only if == NAME1.NAME2"17. Use a dotted name or a literal.

A declaration that a jump skips

A C++ switch jumps into its body, and "transfer of control is not permitted to enter the scope of a variable"4. A variable with an initializer in one case is in scope in the cases below it, so the jump to a later label is an error:

This code does not compile, on purpose.

#include <iostream>

int main() {
    int n = 2;
    switch (n) {
    case 1:
        int x = 10;
        std::cout << x << '\n';
        break;
    case 2:
        std::cout << "two\n";
        break;
    }
}

The fix is braces around the statements of the case, so that x has its own block.

Cost

A compiler can turn a switch into a sequence of comparisons, a binary search, or a jump table. Wikipedia states that "An optimizing compiler such as GCC or Clang may compile a switch statement into either a branch table or a binary search"1. "A branch table allows the program to determine which branch to execute with a single calculation instead of comparing values in a sequence"1. GCC has an option, -fno-jump-tables, to "not use jump tables for switch statements even where it would be more efficient than other code generation strategies"18. So a switch can be faster than a long if chain, but the compiler decides which code to emit.

History

  • Fortran and ALGOL 60. "The earliest Fortran compilers supported the computed goto statement for multi-way branching"1. Early ALGOL compilers had a switch that a goto could index1.
  • 1966. Wirth and Hoare described ALGOL W. "The case expression is supported by languages dating at least as far back as ALGOL-W"1. "Languages such as BCPL, ALGOL-W, and ALGOL-68 introduced forms of this construct which have survived through modern languages"1.
  • 2019. C# 8.0, released in September 2019, added switch expressions12.
  • 2020. JDK 14, released on 17 March 2020, made switch expressions and the case ... -> labels a standard part of Java (JEP 361)1119.
  • 2021. Python 3.10, released on 4 October 2021, added the match statement (PEP 634)2021.

References

  1. Switch statement, Wikipedia, Introduction; Fall through; Compilation; History; Case expression
  2. N1570, ISO/IEC 9899:201x Committee Draft (C11), 6.8.4.2 The switch statement, paragraphs 1, 3 and 5
  3. The Java Language Specification, Java SE 25 Edition, 14.11 The switch Statement; 14.11.1 Switch Blocks; Example 14.11.3-1
  4. switch statement, cppreference.com, Condition; Notes
  5. The Go Programming Language Specification, Switch statements; Expression switches
  6. switch, MDN Web Docs, Description
  7. Selection statements, C# language reference, The switch statement
  8. Conditional Constructs, Bash Reference Manual, case
  9. Conditions and loops, Kotlin documentation, When expressions and statements
  10. More Control Flow Tools, The Python Tutorial, 4.7 match Statements
  11. JEP 361: Switch Expressions, Summary; the header (Release 14)
  12. The history of C#, C# version 8.0 (September 2019), switch expressions
  13. Conditional Expressions, PostgreSQL documentation, 9.18.1 CASE
  14. The match Control Flow Construct, The Rust Programming Language, Introduction; Matches Are Exhaustive
  15. Narrowing, TypeScript Handbook, Equality narrowing; Discriminated unions
  16. about_Switch, PowerShell documentation, Long description; Use break and continue to control the flow
  17. Compound statements, The Python Language Reference, 8.6.4.4 Capture Patterns; 8.6.4.6 Value Patterns
  18. Options for Code Generation Conventions, GCC documentation, -fno-jump-tables
  19. JDK 14, the schedule (General Availability on 17 March 2020)
  20. PEP 634: Structural Pattern Matching: Specification, the header (Python-Version 3.10)
  21. PEP 619: Python 3.10 Release Schedule, Release Schedule (3.10.0 final on Monday, 2021-10-04)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/547T26/text.yaml