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;
}
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
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | When 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. |
| SQL | Native | The 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. |
| Bash | Native | |
| PowerShell | Native | Switch 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. |
| HTML | Does not apply | HTML has no values to branch on. |
| CSS | Does not apply | CSS has no multiway branch on a value; @media and @supports apply rules when a condition is true. |
| Regular expressions | Does not apply | A 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.
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)])
28 30 31
['OK', 'not allowed', 'not found', 'other']
- Verdict: native. Python has no
switch. Amatchwith literal patterns does the same job,|joins several values, andcase _:takes each other value. Only the first case that matches runs. A bare name in acaseis 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;
}
}
stop
slow down
go
two
- Verdict: native. A C++
switchcan test an enumeration, here anenum class. The function has one case for each enumerator and nodefault, and thereturnafter theswitchhandles a value outside the enumerators. In the secondswitch, the braces givedoubledits own block, so the jump tocase 2does not enter its scope.
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));
}
}
}
28 30 31
sat weekend
wed weekday
xyz not a day
- Verdict: native.
daysInuses the statement form withcase ... :labels. Four labels share the group for 30 days, and each group ends withbreak.kinduses a switch expression on aString. Eachcase ... ->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;
}
q: quit
h: help
s: save
?: help
z: unknown
after the switch
- Verdict: native. A C
switchtests an integer, and acharis an integer, so the labels are character constants. Two labels in front of one statement share it. Each case ends withreturn, so no case runs into the next one. The secondswitchhas nodefault, 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)}");
}
q: quit
h: help
z: unknown
1: weekday
7: weekend
9: not a day
- Verdict: native. A C#
switchstatement allows several labels on one section, but a section cannot fall through into the next one, so each section ends withreturnorbreak.Kindis a switch expression. Its arms use the patterns6 or 7and>= 1 and <= 5, and_takes each other value.
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));
pear pome
plum stone fruit
kiwi other
small medium large
- Verdict: native. A JavaScript
switchcan test a string, and two labels in a row share one group. Each case ends withreturn.switch (true)comparestruewith each case expression in order, so it works like anifchain.
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));
}
circle 13
square 9
rectangle 10
- Verdict: native. TypeScript has the
switchof JavaScript. In each case, the compiler narrowsshapeto the member of the union whosekindis that string, soshape.radiusis allowed only in the case for"circle". The three cases cover the union, so the compiler accepts the function with noreturnafter theswitch.
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")
}
}
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 theswitchonxprints onlyone. Aswitchwith no expression compares each case withtrue, so it works like anifchain. Aswitchcan start with a short statement, such asx := 1.
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));
}
28 30 31
small medium large
- Verdict: native. Rust has no
switch. Amatchon literal values does the same job, with|for several values and0..=9for a range. Amatchmust cover every value of its type, so eachmatchhere ends with_.
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
'photo.png' image
'notes.md' text
'run.sh' other
'' no name
- Verdict: native. A Bash
casematches a word against glob patterns, and|joins several patterns. Each clause ends with;;, socasestops after the first match. The last pattern,*, matches each word, so it does the job ofdefault.
Variations and related ideas
- The
ifchain. Aswitchwith 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
switchwhose cases only choose a value. - Pattern matching.
matchin Rust and Python,switchwith patterns in Java and C#, andwhenin Kotlin test the shape of a value and bind its parts. See Pattern matching. - Fall-through. The cases of a C
switchrun into each other unless abreakstops them. See Fall-through. - The task. Write a switch or match writes the same
switchin 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"));
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"));
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))
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
gotocould 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
matchstatement (PEP 634)2021.
References
- Switch statement, Wikipedia, Introduction; Fall through; Compilation; History; Case expression
- N1570, ISO/IEC 9899:201x Committee Draft (C11), 6.8.4.2 The switch statement, paragraphs 1, 3 and 5
- The Java Language Specification, Java SE 25 Edition, 14.11 The switch Statement; 14.11.1 Switch Blocks; Example 14.11.3-1
- switch statement, cppreference.com, Condition; Notes
- The Go Programming Language Specification, Switch statements; Expression switches
- switch, MDN Web Docs, Description
- Selection statements, C# language reference, The switch statement
- Conditional Constructs, Bash Reference Manual, case
- Conditions and loops, Kotlin documentation, When expressions and statements
- More Control Flow Tools, The Python Tutorial, 4.7 match Statements
- JEP 361: Switch Expressions, Summary; the header (Release 14)
- The history of C#, C# version 8.0 (September 2019), switch expressions
- Conditional Expressions, PostgreSQL documentation, 9.18.1 CASE
- The match Control Flow Construct, The Rust Programming Language, Introduction; Matches Are Exhaustive
- Narrowing, TypeScript Handbook, Equality narrowing; Discriminated unions
- about_Switch, PowerShell documentation, Long description; Use break and continue to control the flow
- Compound statements, The Python Language Reference, 8.6.4.4 Capture Patterns; 8.6.4.6 Value Patterns
- Options for Code Generation Conventions, GCC documentation, -fno-jump-tables
- JDK 14, the schedule (General Availability on 17 March 2020)
- PEP 634: Structural Pattern Matching: Specification, the header (Python-Version 3.10)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 547T26 Edit this page History Report an error Markdown