Programming Search⌘K

Conceptcore

Fall-through

Also called fallthrough, fall through, falling through, implicit fall-through, case fall-through, missing break.

In a switch statement with fall-through, control runs from the end of one case into the code of the next case, unless a statement such as break ends the case.

Applies to
core-languages

Idea

A Switch statement jumps to the case label that matches a value. In some languages, the case then has no end of its own. Control runs on through the code of the next case, and the next, until a break or the end of the switch. This is fall-through. Wikipedia describes it: "When control branches to one case, but continues into the subsequent branch, the control flow is called fall through, and allows branching to the same code for multiple values"1.

MDN states the rule for JavaScript: "If break is omitted, execution will proceed to the next case clause, even to the default clause, regardless of whether the value of that clause's expression matches"2. The labels of the next cases are not tested again.

Fall-through can be useful. In this C program, each access level has the rights of the levels under it, so the case for level 3 falls through into the cases for levels 2 and 1:

#include <stdio.h>

static void rights(int level) {
    printf("level %d:", level);
    switch (level) {
    case 3:
        printf(" delete");
        /* no break: fall through to case 2 */
    case 2:
        printf(" write");
        /* no break: fall through to case 1 */
    case 1:
        printf(" read");
        break;
    default:
        printf(" none");
    }
    printf("\n");
}

int main(void) {
    for (int level = 3; level >= 0; level--) {
        rights(level);
    }
    return 0;
}
Output
level 3: delete write read
level 2: write read
level 1: read
level 0: none

But fall-through is also the cause of a common bug: a case that should end, but does not, because its break is missing1.

How it works

  • Labels are only targets. In C and C++, a switch jumps to a label, and the label does nothing more. cppreference states: "case and default labels in themselves do not alter the flow of control"3. The JLS gives the same rule for a Java statement group: "all the block statements in the switch block that follow the switch label are executed, including those that appear after subsequent switch labels"4.
  • Unstructured and structured switches. Wikipedia names two kinds of switch. "An unstructured switch, as in C (and more generally languages influenced by Fortran's computed goto), acts like goto"1. In a structured switch, "as in Pascal-like languages, control jumps from the start of the switch statement to the selected case and at the end of the case, control jumps to the end of the switch statement"1. Only the unstructured kind has fall-through.
  • Ending a case. In a switch with fall-through, a case ends with a statement that leaves the switch: break, return, throw, or goto. A case with no statements, such as each label but the last in case 4: case 6: case 9: case 11:, falls through into the next label. This is how several values share one body.
  • Fall-through on request. Some languages do not fall through, but they have a statement that does it on request. A Go fallthrough statement "transfers control to the first statement of the next case clause in an expression"5 switch. In Bash, "Using ‘;&’ in place of ‘;;’ causes execution to continue with the command-list associated with the next clause, if any"6.

In languages

LanguageVerdictNote
PythonAbsent
C++Native
JavaNative
CNative
C#Idiom
JavaScriptNative
TypeScriptNative
GoNative
RustAbsent
KotlinAbsentWhen compares the value with each branch in order until one branch condition is satisfied, and runs only that branch; there is no fall-through and no statement for it. No example file exists because kotlinc is not installed.
SQLAbsentA CASE expression gives the result of the first WHEN that is true; there is no fall-through. No example file exists.
BashNative
PowerShellAbsentSwitch does not fall through, but it runs the action of each condition that matches the value, unless break or continue stops it. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no switch statement.
CSSDoes not applyCSS has no switch statement.
Regular expressionsDoes not applyA regular expression has no switch statement.
Language Falls through by default Fall-through on request How a case ends
C yes3 leave out break; mark it with the C23 attribute fallthrough;7 break, return, goto
C++ yes3 leave out break; mark it with the C++17 attribute fallthrough;8 break, return, throw
Java yes with case ... : labels; no with case ... -> labels49 leave out break break, or the end of a -> rule
JavaScript, TypeScript yes2 leave out break break, return, throw
C# no; a compile error, except for a section with no statements10 goto case and goto default11 break, goto, return10
Go no5 fallthrough5 the end of the case
Bash no with ;;6 ;&, or ;;& to test the next patterns6 ;;
Python, Rust, Kotlin no121314 none the end of the case
PowerShell runs each condition that matches15 none break or continue15
  • C and C++. A case without break falls through. The C23 and C++17 standards added the statement fallthrough;, which marks a fall-through as intentional. cppreference states that it "Indicates that the fall through from the previous case label is intentional and should not be diagnosed by a compiler that warns on fallthrough"87.
  • Java. A switch with case ... : labels falls through, as in C. JEP 361 added case ... -> labels "(with no fall through)"9. A -> rule runs its own code "and nothing else"4.
  • C#. "Within a switch statement, control can't fall through from one switch section to the next"10. The C# reference adds: "Falling through from one switch section to the next generates a compiler error"10. To get the effect of fall-through, a section uses goto case or goto default11.
  • Go. A case ends by itself. A fallthrough statement "may appear as the last statement of all but the last clause of an expression switch"5. A type switch cannot use fallthrough5.
  • Bash. A clause ends with ;;, ;& or ;;&. ;& runs the commands of the next clause. ;;& is different: it causes "the shell to test the patterns in the next clause, if any, and execute any associated command-list if the match succeeds"6.
  • Python, Rust and Kotlin. These languages run one case only. In Python, "Only the first pattern that matches gets executed"12. In Rust, "If a pattern matches the value, the code associated with that pattern is executed"13, and the match ends. Kotlin when compares the value "against each branch in order until one branch condition is satisfied"14.
  • PowerShell. A PowerShell switch does not fall through, but it does not stop at the first match either: "If the value matches multiple conditions, the action for each condition is executed"15. break stops this.
PythonGitHub
def rights(level):
    out = []
    match level:
        case 3:
            out.append("delete")
        case 2:
            out.append("write")
        case 1:
            out.append("read")
        case _:
            out.append("none")
    return out


def rights_with_ifs(level):
    out = []
    if level >= 3:
        out.append("delete")
    if level >= 2:
        out.append("write")
    if level >= 1:
        out.append("read")
    return out or ["none"]


print(rights(3), rights_with_ifs(3))
print(rights(0), rights_with_ifs(0))
Output
['delete'] ['delete', 'write', 'read']
['none'] ['none']
  • Verdict: absent. A match statement runs only the first case that matches, so there is no fall-through and no break. To run the code of several cases, use separate if statements.
#include <iostream>
#include <string>

std::string rights(int level) {
    std::string out;
    switch (level) {
    case 3:
        out += " delete";
        [[fallthrough]];
    case 2:
        out += " write";
        [[fallthrough]];
    case 1:
        out += " read";
        break;
    default:
        out += " none";
        break;
    }
    return out;
}

int main() {
    std::cout << 3 << ':' << rights(3) << '\n';
    std::cout << 2 << ':' << rights(2) << '\n';
    std::cout << 0 << ':' << rights(0) << '\n';
}
Output
3: delete write read
2: write read
0: none
  • Verdict: native. A C++ case without break falls through. The C++17 statement fallthrough; marks an intentional fall-through; it must come just before a case or default label.
JavaGitHub
public class Main {
    static String colon(int level) {
        StringBuilder out = new StringBuilder();
        switch (level) {
            case 3:
                out.append(" delete");
            case 2:
                out.append(" write");
            case 1:
                out.append(" read");
                break;
            default:
                out.append(" none");
        }
        return out.toString();
    }

    static String arrow(int level) {
        StringBuilder out = new StringBuilder();
        switch (level) {
            case 3 -> out.append(" delete");
            case 2 -> out.append(" write");
            case 1 -> out.append(" read");
            default -> out.append(" none");
        }
        return out.toString();
    }

    public static void main(String[] args) {
        System.out.println("colon 3:" + colon(3));
        System.out.println("arrow 3:" + arrow(3));
    }
}
Output
colon 3: delete write read
arrow 3: delete
  • Verdict: native. A switch with case ... : labels falls through, as in C. A switch with case ... -> labels runs only the code of the matching rule, so arrow(3) gives only delete.
#include <stdio.h>

static void rights(int level) {
    printf("%d:", level);
    switch (level) {
    case 3:
        printf(" delete");
        [[fallthrough]];
    case 2:
        printf(" write");
        [[fallthrough]];
    case 1:
        printf(" read");
        break;
    default:
        printf(" none");
        break;
    }
    printf("\n");
}

int main(void) {
    rights(3);
    rights(1);
    rights(0);
    return 0;
}
Output
3: delete write read
1: read
0: none
  • Verdict: native. A C case without break falls through into the next case. The C23 statement fallthrough; marks the fall-through as intentional, so a compiler that warns on fall-through does not warn here.
using System;

static string Rights(int level)
{
    string out_ = "";
    switch (level)
    {
        case 3:
            out_ += " delete";
            goto case 2;
        case 2:
            out_ += " write";
            goto case 1;
        case 1:
            out_ += " read";
            break;
        default:
            out_ += " none";
            break;
    }
    return out_;
}

Console.WriteLine("3:" + Rights(3));
Console.WriteLine("2:" + Rights(2));
Console.WriteLine("0:" + Rights(0));
Output
3: delete write read
2: write read
0: none
  • Verdict: idiom. C# does not allow fall-through from a section with statements: each section ends with break, goto, return or throw. goto case 2; jumps to the section for 2, and so gives the effect of fall-through on request.
JavaScriptGitHub
function rights(level) {
  const out = [];
  switch (level) {
    case 3:
      out.push("delete");
    // falls through
    case 2:
      out.push("write");
    // falls through
    case 1:
      out.push("read");
      break;
    default:
      out.push("none");
  }
  return out.join(" ");
}

console.log(rights(3));
console.log(rights(2));
console.log(rights(9));
Output
delete write read
write read
none
  • Verdict: native. A JavaScript case without break falls through into the next case, and into default too. A comment such as // falls through tells the reader that the fall-through is intentional.
TypeScriptGitHub
function rights(level: number): string[] {
  const out: string[] = [];
  switch (level) {
    case 3:
      out.push("delete");
    // falls through
    case 2:
      out.push("write");
    // falls through
    case 1:
      out.push("read");
      break;
    default:
      out.push("none");
  }
  return out;
}

console.log(rights(3).join(" "));
console.log(rights(1).join(" "));
Output
delete write read
read
  • Verdict: native. TypeScript has the switch of JavaScript, with the same fall-through. The compiler option noFallthroughCasesInSwitch reports an error for each non-empty case that does not end with break, return or throw.
package main

import "fmt"

func rights(level int) []string {
	var out []string
	switch level {
	case 3:
		out = append(out, "delete")
		fallthrough
	case 2:
		out = append(out, "write")
		fallthrough
	case 1:
		out = append(out, "read")
	default:
		out = append(out, "none")
	}
	return out
}

func main() {
	fmt.Println(rights(3))
	fmt.Println(rights(1))
	fmt.Println(rights(0))
}
Output
[delete write read]
[read]
[none]
  • Verdict: native. A Go case ends by itself, so case 1 does not run on into default. The fallthrough statement, as the last statement of a case, moves control into the next case on request. It does not test the expression of the next case.
RustGitHub
fn rights(level: u32) -> Vec<&'static str> {
    let mut out = Vec::new();
    match level {
        3 => out.push("delete"),
        2 => out.push("write"),
        1 => out.push("read"),
        _ => out.push("none"),
    }
    out
}

fn rights_cumulative(level: u32) -> Vec<&'static str> {
    let all = ["read", "write", "delete"];
    let n = (level as usize).min(all.len());
    let mut out: Vec<&str> = all[..n].to_vec();
    out.reverse();
    out
}

fn main() {
    println!("{:?} {:?}", rights(3), rights_cumulative(3));
    println!("{:?} {:?}", rights(1), rights_cumulative(1));
}
Output
["delete"] ["delete", "write", "read"]
["read"] ["read"]
  • Verdict: absent. A match runs the code of the first arm that matches, and then the match ends. Rust has no fall-through and no statement for it, so code that needs the effect of several arms computes it in another way, as rights_cumulative does.
BashGitHub
rights() {
  local out=""
  case $1 in
    3) out+=" delete" ;&
    2) out+=" write" ;&
    1) out+=" read" ;;
    *) out+=" none" ;;
  esac
  echo "$1:$out"
}

rights 3
rights 2
rights 0

kind() {
  case $1 in
    [0-9]*) printf 'starts with a digit' ;;&
    *0) printf ', ends with 0' ;;&
    *) printf '\n' ;;
  esac
}

kind 10
kind 17
Output
3: delete write read
2: write read
0: none
starts with a digit, ends with 0
starts with a digit
  • Verdict: native. A clause that ends with ;; does not fall through. A clause that ends with ;& runs the commands of the next clause. A clause that ends with ;;& tests the patterns of the next clauses, and runs each clause that matches.
  • Warnings. Wikipedia notes that "often fall through code results in a warning from a code quality tool such as lint"1. GCC has -Wimplicit-fallthrough, which warns "when a switch case falls through"16. The warning "does not warn when the last statement of a case cannot fall through, e.g. when there is a return statement"16. TypeScript has the compiler option noFallthroughCasesInSwitch. It reports "errors for fallthrough cases in switch statements" and "Ensures that any non-empty case inside a switch statement includes either break, return, or throw"17.
  • Markers. A marker tells the compiler and the reader that a fall-through is intentional. GCC accepts a comment such as /* FALLTHRU */ before the next label, the attribute __attribute__ ((fallthrough)), and the standard fallthrough;16.
  • Several values in one case. Stacked labels with no statements are the most common use of fall-through. Languages without fall-through give a list of values in one case instead, such as case 4, 6, 9, 11: in Go or case 4 | 6 | 9 | 11: in Python. Write a switch or match shows both forms.
  • Duff's device. Duff's device puts the labels of a switch inside a do loop, and jumps into the middle of the loop. "Duff implemented this technique in C by using C's case label fall-through feature to jump into the unrolled body"18.

Pitfalls

A missing break

A case that should end, but has no break, runs the code of the next case. Wikipedia states: "a common mistake is to accidentally omit the keyword, causing unintentional fall through and often a bug"1. The JLS gives an example with three cases and adds: "Fall through can be the cause of subtle bugs"4. Here the case for 200 has no break:

This code runs but gives a wrong answer on purpose.

public class Main {
    static String status(int code) {
        String text;
        switch (code) {
            case 200:
                text = "ok";
            case 404:
                text = "not found";
                break;
            default:
                text = "other";
        }
        return text;
    }

    public static void main(String[] args) {
        System.out.println(status(200) + ", " + status(404) + ", " + status(500));
    }
}
Output
not found, not found, other

The fix is a break at the end of the case for 200, or a -> rule for each case. A -> rule runs its own code "and nothing else"4.

Fall-through into default

The default clause is a label too, so a case can fall through into it. MDN states that execution proceeds "even to the default clause"2:

This code runs but gives a wrong answer on purpose.

function describe(n) {
  const parts = [];
  switch (n) {
    case 0:
      parts.push("zero");
    default:
      parts.push("not zero");
  }
  return parts.join(", ");
}

console.log(describe(0));
console.log(describe(5));
Output
zero, not zero
not zero

A Go fallthrough does not test the next case

A Go fallthrough goes to "the first statement of the next case clause"5. It does not test the expression of that case:

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

func main() {
	n := 5
	switch {
	case n > 0:
		fmt.Println("positive")
		fallthrough
	case n > 100:
		fmt.Println("more than 100")
	}
}
Output
positive
more than 100

5 is not more than 100, but the second case runs. To test the next condition, use a second switch or an if.

Fall-through in C# does not compile

Code that relies on fall-through does not move to C# without change. "Every switch section must end with a break, goto, or return"10:

This code does not compile, on purpose.

using System;

static void Rights(int level)
{
    switch (level)
    {
        case 2:
            Console.Write(" write");
        case 1:
            Console.Write(" read");
            break;
    }
    Console.WriteLine();
}

Rights(2);

The fix is goto case 1; at the end of the section for 211.

Cost

Fall-through adds no work at run time. In an unstructured switch, which "acts like goto"1, control simply goes on to the next statement. The cost is in reading the code: a reader must check each case for a break to know where the case ends. Markers such as fallthrough; and warnings such as -Wimplicit-fallthrough reduce this cost816.

History

  • 1983. "Its discovery is credited to Tom Duff in November 1983, when Duff was working for Lucasfilm and used it to speed up a real-time animation program"18. The Jargon File called Duff's device "the most dramatic use yet seen of fall through in C"18. Duff said: "This code forms some sort of argument in that debate, but I'm not sure whether it's for or against"18.
  • C++17 and C23. C++17 added the fallthrough attribute8, and C23 added the same attribute to C7.
  • 2020. JEP 361 made case ... -> labels with no fall through a standard part of Java in JDK 149. The JEP names "the default control flow behavior between switch labels (fall through)" as one of the problems of the old switch9.

References

  1. Switch statement, Wikipedia, Fall through
  2. switch, MDN Web Docs, Breaking and fall-through
  3. switch statement, cppreference.com, Control flow transfer
  4. The Java Language Specification, Java SE 25 Edition, 14.11.3 Execution of a switch Statement; Example 14.11.3-1
  5. The Go Programming Language Specification, Expression switches; Fallthrough statements
  6. Conditional Constructs, Bash Reference Manual, case
  7. C attribute: fallthrough (since C23), cppreference.com, Explanation
  8. C++ attribute: fallthrough (since C++17), cppreference.com, Explanation
  9. JEP 361: Switch Expressions, Summary; Motivation
  10. Selection statements, C# language reference, The switch statement
  11. Jump statements, C# language reference, The goto statement
  12. More Control Flow Tools, The Python Tutorial, 4.7 match Statements
  13. The match Control Flow Construct, The Rust Programming Language, Introduction
  14. Conditions and loops, Kotlin documentation, When expressions and statements
  15. about_Switch, PowerShell documentation, Use break and continue to control the flow
  16. Options to Request or Suppress Warnings, GCC documentation, -Wimplicit-fallthrough
  17. noFallthroughCasesInSwitch, TSConfig Reference, the whole page
  18. Duff's device, Wikipedia, Introduction; Mechanism

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/PWSEXB/text.yaml