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;
}
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, orgoto. A case with no statements, such as each label but the last incase 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
fallthroughstatement "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
| Language | Verdict | Note |
|---|---|---|
| Python | Absent | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Idiom | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Absent | |
| Kotlin | Absent | When 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. |
| SQL | Absent | A CASE expression gives the result of the first WHEN that is true; there is no fall-through. No example file exists. |
| Bash | Native | |
| PowerShell | Absent | Switch 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. |
| HTML | Does not apply | HTML has no switch statement. |
| CSS | Does not apply | CSS has no switch statement. |
| Regular expressions | Does not apply | A 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
breakfalls through. The C23 and C++17 standards added the statementfallthrough;, 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 addedcase ... ->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 caseorgoto default11. - Go. A case ends by itself. A
fallthroughstatement "may appear as the last statement of all but the last clause of an expression switch"5. A type switch cannot usefallthrough5. - Bash. A clause ends with
;;,;∨;&.;&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
matchends. Kotlinwhencompares the value "against each branch in order until one branch condition is satisfied"14. - PowerShell. A PowerShell
switchdoes 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.breakstops this.
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))
['delete'] ['delete', 'write', 'read']
['none'] ['none']
- Verdict: absent. A
matchstatement runs only the first case that matches, so there is no fall-through and nobreak. To run the code of several cases, use separateifstatements.
#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';
}
3: delete write read
2: write read
0: none
- Verdict: native. A C++ case without
breakfalls through. The C++17 statementfallthrough;marks an intentional fall-through; it must come just before acaseordefaultlabel.
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));
}
}
colon 3: delete write read
arrow 3: delete
- Verdict: native. A switch with
case ... :labels falls through, as in C. A switch withcase ... ->labels runs only the code of the matching rule, soarrow(3)gives onlydelete.
#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;
}
3: delete write read
1: read
0: none
- Verdict: native. A C case without
breakfalls through into the next case. The C23 statementfallthrough;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));
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,returnorthrow.goto case 2;jumps to the section for 2, and so gives the effect of fall-through on request.
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));
delete write read
write read
none
- Verdict: native. A JavaScript case without
breakfalls through into the next case, and intodefaulttoo. A comment such as// falls throughtells the reader that the fall-through is intentional.
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(" "));
delete write read
read
- Verdict: native. TypeScript has the switch of JavaScript, with the same fall-through. The compiler option
noFallthroughCasesInSwitchreports an error for each non-empty case that does not end withbreak,returnorthrow.
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))
}
[delete write read]
[read]
[none]
- Verdict: native. A Go case ends by itself, so case 1 does not run on into
default. Thefallthroughstatement, 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.
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));
}
["delete"] ["delete", "write", "read"]
["read"] ["read"]
- Verdict: absent. A
matchruns the code of the first arm that matches, and then thematchends. Rust has no fall-through and no statement for it, so code that needs the effect of several arms computes it in another way, asrights_cumulativedoes.
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
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.
Variations and related ideas
- 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 optionnoFallthroughCasesInSwitch. 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 standardfallthrough;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 orcase 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
doloop, 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));
}
}
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));
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")
}
}
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
fallthroughattribute8, 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
- Switch statement, Wikipedia, Fall through
- switch, MDN Web Docs, Breaking and fall-through
- switch statement, cppreference.com, Control flow transfer
- The Java Language Specification, Java SE 25 Edition, 14.11.3 Execution of a switch Statement; Example 14.11.3-1
- The Go Programming Language Specification, Expression switches; Fallthrough statements
- Conditional Constructs, Bash Reference Manual, case
- C attribute: fallthrough (since C23), cppreference.com, Explanation
- C++ attribute: fallthrough (since C++17), cppreference.com, Explanation
- JEP 361: Switch Expressions, Summary; Motivation
- Selection statements, C# language reference, The switch statement
- Jump statements, C# language reference, The goto statement
- More Control Flow Tools, The Python Tutorial, 4.7 match Statements
- The match Control Flow Construct, The Rust Programming Language, Introduction
- Conditions and loops, Kotlin documentation, When expressions and statements
- about_Switch, PowerShell documentation, Use break and continue to control the flow
- Options to Request or Suppress Warnings, GCC documentation, -Wimplicit-fallthrough
- noFallthroughCasesInSwitch, TSConfig Reference, the whole page
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag PWSEXB Edit this page History Report an error Markdown