Conceptcore
Control flow
Also called control flow, flow of control, order of execution, control structure, control flow statement, sequence selection iteration, branch, jump, abrupt completion, normal completion.
Control flow is the order in which a program runs its statements. Sequence, selection, iteration, jumps, calls and exceptions are the ways to change that order.
- Applies to
- core-languages
Idea
A program is a list of statements, but it does not always run them from top to bottom once. It skips some statements, runs others many times, leaves a loop early, calls a function and comes back, or jumps to an error handler. Control flow is the order in which the statements actually run, and the control structures of a language are the tools that choose that order.
def classify(numbers):
trace = []
for n in numbers: # iteration: run the body once for each number
if n < 0: # selection: choose one of two paths
trace.append(f"{n} skip")
continue # jump to the next iteration
if n == 0:
trace.append("0 stop")
break # jump out of the loop
trace.append(f"{n} keep")
return trace # jump back to the caller
print(classify([3, -1, 4, 0, 5]))
def parse(text):
try:
value = int(text)
print("parsed", value) # skipped when int() raises
return value
except ValueError:
print("not a number:", text) # the exception jumps here
return None
finally:
print("finally runs on every path")
parse("42")
parse("4x2")
['3 keep', '-1 skip', '4 keep', '0 stop']
parsed 42
finally runs on every path
not a number: 4x2
finally runs on every path
classify uses the main forms of control flow. The for loop runs its body once for each number, the if statements choose a path, continue jumps to the next number, break leaves the loop at 0, so 5 is never seen, and return gives control back to the caller. In parse, the call int("4x2") raises an exception, so control jumps over the rest of the try block to the except block. The finally block runs on both paths.
How it works
Sequence and transfer. Wikipedia says that "control flow (or flow of control) describes how execution progresses from one command to the next"1. By default, control goes to the next statement, "except when a command transfers control to another point"1. At the machine level, "a control flow instruction often alters the program counter and is either an unconditional branch (a.k.a. jump) or a conditional branch"1. The control structures of a high-level language compile to such branches.
Three structures are enough. The structured program theorem states that any computable function can be computed with "only the following three control structures"2: sequence, "Executing one subprogram, and then another subprogram"; selection, "Executing one of two subprograms according to the value of a boolean expression"; and iteration, "Repeatedly executing a subprogram as long as a boolean expression is true"2. Crafting Interpreters says the same in terms of jumps: "Conditional or branching control flow is used to not execute some piece of code", and "Looping control flow executes a chunk of code more than once. It jumps back so that you can do something again"3. With arithmetic, a little control flow and unbounded memory, a language is Turing-complete3.
The forms in real languages. Languages add more forms to the three, because they make programs shorter and clearer:
- selection:
if,else if,switch,matchand the conditional expressionc ? a : b, - iteration:
while,do while,for, for-each andloop, - jumps:
break,continue,return,gotoand labeledbreak, - calls: a function call jumps to the function and a return jumps back,
- exceptions and panics: a
throwjumps to the nearest matching handler, through any number of calls, - suspension:
yieldandawaitstop a function and resume it later.
The C reference names five kinds of statements: "compound statements", "expression statements", "selection statements", "iteration statements" and "jump statements"4. In C#, "The jump statements unconditionally transfer control"5.
Normal and abrupt completion. Java describes control flow with a precise rule. "The sequence of execution of a program is controlled by statements"6. A statement completes normally, or it completes abruptly, and "An abrupt completion always has an associated reason"6: a break, a continue, a return, a throw or a yield. A try statement with finally catches every abrupt completion, runs its cleanup and then continues the same completion. Go has a similar rule: "A terminating statement interrupts the regular flow of control in a block"7, and the compiler uses it to check that a function always returns.
Statements and expressions. In C, Java and Python, most control structures are statements: "The if, while and for statements implement traditional control flow constructs"8. In Rust, if, match and loop are expressions, so they give a value. The Rust book says that "The most common constructs that let you control the flow of execution of Rust code are if expressions and loops"9.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the control flow statements of JavaScript, and the compiler follows each path to narrow the types of variables, for example after a test for null. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has if, when, for, while, do while and try, and if, when and try are expressions that give values. break, continue and return take labels. No example file exists because kotlinc is not installed. |
| SQL | Idiom | A SQL query states a result and not an order of steps. CASE chooses a value in an expression, and procedural extensions such as PL/pgSQL add IF, LOOP and WHILE. No example file exists. |
| Bash | Native | Bash has if, case, while, until, for, select, break and continue, and the exit status of a command decides each branch. No example file exists. |
| PowerShell | Native | PowerShell has if, switch, while, do, for, foreach, labeled break and continue, try, catch and finally, and the trap statement. No example file exists because pwsh is not installed. |
| HTML | Does not apply | An HTML document describes content and does not run statements, so it has no control flow. |
| CSS | Does not apply | CSS rules have no order of execution. The cascade, specificity and conditional rules such as @media decide which declarations apply. |
| Regular expressions | Idiom | A regex engine tries alternatives with | and repeats with *, + and ?, and a backtracking engine goes back to try another path when a match fails. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | if, while, for, match, try, with; else on loops; generators with yield |
| JavaScript | native | if, switch, loops, labels, try; promises and async functions for later steps |
| TypeScript | native | the statements of JavaScript; the compiler narrows types along each path |
| Java | native | statements with normal and abrupt completion; switch with arrows; checked exceptions |
| Kotlin | native | if, when and try are expressions; labeled break and return |
| C# | native | if, switch, loops, goto case; no fallthrough; yield return iterators |
| Go | native | if, switch, one for loop, goto, defer, panic and recover |
| Rust | native | if, match and loop are expressions; break with a value; the ? operator |
| C | native | selection, iteration and jump statements; goto; setjmp and longjmp |
| C++ | native | the statements of C; exceptions that run destructors; fallthrough |
| Bash | native | if, case, while, for, break, continue; the exit status decides each branch |
| PowerShell | native | if, switch, loops, labeled break, try, catch, finally and trap |
| SQL | idiom | a query is declarative and has no order of statements; CASE chooses a value, and procedural extensions add loops |
| Regex | idiom | the engine tries alternatives and backtracks, and |, ?, * and + choose and repeat |
| HTML | n/a | a document has no execution order of statements |
| CSS | n/a | style rules have no control flow; the cascade decides which declaration wins |
All general-purpose languages have sequence, selection and iteration, so the differences are in the details: which structures are expressions, whether a switch case falls through, and how a program leaves a block early.
The example files show these details. Python uses else on a loop, shows that finally runs before a return finishes, and shows how a generator gives control back to its caller at each yield. JavaScript shows a switch with two cases that share one body, and the order of synchronous code, promise callbacks and timers. Java uses a switch expression with arrows, an exception that moves control to a catch block, do while, break and continue. C# uses goto case, a lazy iterator and a switch expression. Go shows the last-in, first-out order of defer, a panic that recover stops, fallthrough and goto. Rust uses if, loop and match as expressions and returns early with ?. C shows switch fallthrough, the goto cleanup idiom and a non-local jump with longjmp. C++ shows that an exception runs the destructors of each scope that it leaves.
# The else of a loop runs only when the loop ends without break.
def find(items, target):
for i, item in enumerate(items):
if item == target:
print("found at", i)
break
else:
print("not found")
find(["a", "b", "c"], "b")
find(["a", "b", "c"], "z")
# finally runs even when the try block returns.
def order():
try:
print("try")
return "from try"
finally:
print("finally")
print(order())
# A generator gives control back to the caller at each yield, and resumes later.
def counter():
print("start")
yield 1
print("resume")
yield 2
print("end")
for n in counter():
print("got", n)
# A conditional expression chooses a value, not a statement.
n = 7
print("odd" if n % 2 else "even")
found at 1
not found
try
finally
from try
start
got 1
resume
got 2
end
odd
- Verdict: native. The
elseof aforloop runs only when the loop ends withoutbreak.finallyruns afterreturncomputes its value and before the function returns. A generator stops at eachyield, gives control to theforloop, and resumes at the next request. A conditional expression chooses a value.
#include <print>
#include <stdexcept>
#include <string>
// A destructor runs when control leaves the scope, by any path.
struct Guard {
std::string name;
~Guard() { std::println("leave {}", name); }
};
void step(int n) {
Guard g{"step " + std::to_string(n)};
if (n == 2) throw std::runtime_error("failed at 2");
std::println("step {} done", n);
}
int main() {
// An exception unwinds the stack and runs the destructors on the way.
try {
for (int n = 1; n <= 3; n++) step(n);
} catch (const std::exception& e) {
std::println("caught: {}", e.what());
}
// [[fallthrough]] states that a case continues into the next one on purpose.
for (int n : {1, 2}) {
switch (n) {
case 1:
std::print("one ");
[[fallthrough]];
case 2:
std::println("one-or-two");
break;
}
}
// if with an initializer limits the variable to the statement.
if (int r = 17 % 5; r != 0) std::println("remainder {}", r);
}
step 1 done
leave step 1
leave step 2
caught: failed at 2
one one-or-two
one-or-two
remainder 2
- Verdict: native. An exception at step 2 unwinds the stack, and the destructor of each
Guardruns as control leaves its scope.fallthroughstates that a case continues into the next one on purpose. Anifwith an initializer limits the variable to the statement.
public class Main {
static String grade(int score) {
// A switch with arrows has no fallthrough; each case is one branch.
return switch (score / 10) {
case 10, 9 -> "A";
case 8 -> "B";
case 7 -> "C";
default -> "F";
};
}
static int parse(String s) {
// An exception completes the try block abruptly, and control goes to the catch.
try {
int v = Integer.parseInt(s);
System.out.println("parsed " + v);
return v;
} catch (NumberFormatException e) {
System.out.println("bad input " + s);
return -1;
} finally {
System.out.println("finally " + s);
}
}
public static void main(String[] args) {
System.out.println(grade(95) + " " + grade(81) + " " + grade(42));
parse("12");
parse("x");
// do-while runs its body before the first test.
int n = 0;
do {
n++;
} while (n < 0);
System.out.println("do-while ran " + n + " time");
// A loop with break and continue.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue;
if (i > 7) break;
sb.append(i).append(' ');
}
System.out.println(sb.toString().trim());
}
}
A B F
parsed 12
finally 12
bad input x
finally x
do-while ran 1 time
1 3 5 7
- Verdict: native. A
switchexpression with arrows has no fallthrough.Integer.parseInt("x")throws, so thetryblock completes abruptly, control goes tocatch, andfinallyruns on both paths.do whileruns its body once before the first test.continueskips the even numbers andbreakstops the loop after 7.
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
static jmp_buf env;
static void inner(int fail) {
if (fail) {
longjmp(env, 42); /* jump back to setjmp, through all callers */
}
printf("inner ok\n");
}
/* goto to one cleanup label per resource is a common C idiom. */
static int work(int fail) {
int rc = -1;
char *a = malloc(16);
if (a == NULL) goto out;
char *b = fail ? NULL : malloc(16); /* fail simulates an allocation failure */
if (b == NULL) goto free_a;
printf("both allocated ");
rc = 0;
free(b);
free_a:
free(a);
out:
return rc;
}
int main(void) {
/* A switch case falls through into the next case unless it breaks. */
for (int n = 1; n <= 3; n++) {
switch (n) {
case 1:
printf("one ");
/* fall through */
case 2:
printf("one-or-two ");
break;
default:
printf("other ");
}
}
printf("\n");
int ok = work(0);
int failed = work(1);
printf("%d %d\n", ok, failed);
int code = setjmp(env);
if (code == 0) {
inner(0);
inner(1);
printf("not reached\n");
} else {
printf("longjmp returned %d\n", code);
}
return 0;
}
one one-or-two one-or-two other
both allocated 0 -1
inner ok
longjmp returned 42
- Verdict: native. A
switchcase withoutbreakfalls through, so1prints both labels. Thegotocleanup idiom jumps to the label that frees what was allocated, and the simulated failure returns-1.longjmpjumps frominnerback tosetjmpinmain, so the line after the second call does not run.
using System.Collections.Generic;
// C# forbids fallthrough between cases; goto case jumps to another case.
static string Describe(int n)
{
switch (n)
{
case 0:
return "zero";
case 1:
goto case 2;
case 2:
return "small";
default:
return "large";
}
}
Console.WriteLine($"{Describe(0)} {Describe(1)} {Describe(9)}");
// An iterator runs lazily: its body runs only when the caller asks for the next value.
static IEnumerable<int> Numbers()
{
Console.WriteLine("start");
yield return 1;
Console.WriteLine("after 1");
yield return 2;
}
foreach (var n in Numbers())
{
Console.WriteLine($"got {n}");
}
// finally runs when control leaves the try block by return.
static int WithFinally()
{
try
{
return 1;
}
finally
{
Console.WriteLine("finally");
}
}
Console.WriteLine(WithFinally());
// A switch expression and a conditional operator choose a value.
int t = 25;
Console.WriteLine(t switch { < 10 => "cold", < 25 => "mild", _ => "warm" });
Console.WriteLine(t % 2 == 0 ? "even" : "odd");
zero small large
start
got 1
after 1
got 2
finally
1
warm
odd
- Verdict: native. C# forbids fallthrough between cases, so
case 1usesgoto case 2to share its code. The body of an iterator runs only whenforeachasks for the next value, so the lines interleave.finallyruns whenreturnleaves thetryblock. Aswitchexpression with relational patterns and the conditional operator choose values.
// A switch case without break falls through into the next case.
function days(month) {
switch (month) {
case "feb":
return 28;
case "apr":
case "jun":
return 30;
default:
return 31;
}
}
console.log(days("feb"), days("jun"), days("jan"));
// finally runs after the return value is computed and before the function returns.
function f() {
try {
return "try";
} finally {
console.log("finally runs first");
}
}
console.log(f());
// Asynchronous code runs later: synchronous code first, then promise callbacks, then timers.
const order = [];
setTimeout(() => {
order.push("timer");
console.log(order.join(" "));
}, 0);
Promise.resolve().then(() => order.push("promise"));
order.push("sync");
// && and ?. also choose whether code runs.
const user = null;
console.log(user?.name ?? "no user", user && user.name);
28 30 31
finally runs first
try
no user null
sync promise timer
- Verdict: native. The cases
"apr"and"jun"share one body, because a case withoutbreakorreturnfalls through.finallyruns before the function returns. Synchronous code runs first, then the promise callback, then the timer, so the order issync promise timer.?.,??and&&decide whether the code to their right runs.
package main
import (
"errors"
"fmt"
)
// Deferred calls run when the function returns, last in first out.
func deferred() {
for i := 1; i <= 3; i++ {
defer fmt.Println("deferred", i)
}
fmt.Println("body done")
}
// recover in a deferred function stops a panic and lets the function return.
func safeDiv(a, b int) (q int, err error) {
defer func() {
if r := recover(); r != nil {
err = errors.New(fmt.Sprint(r))
}
}()
return a / b, nil
}
func main() {
deferred()
fmt.Println(safeDiv(7, 2))
fmt.Println(safeDiv(1, 0))
// A switch case does not fall through unless it says fallthrough.
for _, n := range []int{1, 2, 3} {
switch n {
case 1:
fmt.Println("one")
fallthrough
case 2:
fmt.Println("one or two")
default:
fmt.Println("other")
}
}
// goto jumps to a label in the same function.
i := 0
loop:
if i < 3 {
i++
goto loop
}
fmt.Println("i =", i)
}
body done
deferred 3
deferred 2
deferred 1
3 <nil>
0 runtime error: integer divide by zero
one
one or two
one or two
other
i = 3
- Verdict: native. Deferred calls run when the function returns, in last-in, first-out order. A division by zero panics, and
recoverin a deferred function turns the panic into an error. Aswitchcase does not fall through unless it saysfallthrough.gotojumps back to a label to make a loop.
use std::num::ParseIntError;
// if, match and loop are expressions, so they give values.
fn sign(n: i32) -> &'static str {
if n < 0 {
"negative"
} else if n == 0 {
"zero"
} else {
"positive"
}
}
// The ? operator returns early with the error.
fn sum(a: &str, b: &str) -> Result<i32, ParseIntError> {
let x: i32 = a.parse()?;
let y: i32 = b.parse()?;
Ok(x + y)
}
fn main() {
println!("{} {} {}", sign(-5), sign(0), sign(8));
// break can give a value to the loop expression.
let mut n = 1;
let first = loop {
n *= 3;
if n > 50 {
break n;
}
};
println!("{first}");
// match must cover every value.
let size = match first {
0..=9 => "one digit",
10..=99 => "two digits",
_ => "more",
};
println!("{size}");
println!("{:?} {}", sum("2", "3"), sum("2", "x").is_err());
// while let runs while a pattern matches.
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
print!("{top} ");
}
println!();
}
negative zero positive
81
two digits
Ok(5) true
3 2 1
- Verdict: native.
ifandmatchare expressions, sosignhas noreturn.break ngives a value to theloop, andmatchmust cover every value. The?operator returns the parse error early.while letruns whilepopreturnsSome.
Variations and related ideas
- Structured and unstructured flow.
gotocan jump to any label, so the order of execution can be hard to see from the text. Structured programming limits a program to blocks with one entry and one exit. - Non-local exits. Exceptions,
longjmpand labeledbreakleave several levels at once. See exception handling. - Control flow in expressions.
&&,||and??decide whether their right operand runs. See short-circuit evaluation. - Pattern matching.
matchchooses a branch by the shape of a value. See pattern matching. - Asynchronous flow. With callbacks, promises and
await, the next step runs when an event happens, not when the previous statement ends. - Control flow graphs. A compiler represents a function as a graph of basic blocks and the jumps between them, and uses it for optimization and analysis.
Pitfalls
- Fallthrough. In C, C++ and JavaScript, a
switchcase withoutbreakruns into the next case. C# forbids this, and Go needs the keywordfallthrough. - Hidden exits. An exception can leave any call. Code that changes state in several steps must clean up on that path too, with
finally,deferor destructors. returninfinally. In Java, JavaScript and Python, areturnin afinallyblock replaces the exception or the value of thetryblock.- Deep nesting. Many levels of
ifmake the order hard to follow. Early returns and guard clauses keep the main path flat. - Off by one. A loop that tests
<=instead of<runs one time too many.
Cost
A branch is cheap, but a processor guesses the direction of each branch to keep its pipeline full, and a wrong guess costs some cycles. Loops over data that give random branch directions are slower than loops with regular branches. Function calls cost a few instructions, and compilers inline small functions to remove them. Exceptions are cheap when no exception is thrown in C++, Java and C#, and expensive when one is.
History
Machine code had jumps and conditional jumps from the start, and early high-level languages such as FORTRAN had GO TO and IF statements. In May 1966, Corrado Böhm and Giuseppe Jacopini published "Flow Diagrams, Turing Machines and Languages with Only Two Formation Rules" in the Communications of the ACM2, which showed that sequence, selection and iteration are enough. In 1968, Dijkstra wrote: "The go to statement as it stands is just too primitive, it is too much an invitation to make a mess of one's program"10. His letter appeared in Comm. ACM 11 "under the title “Go To Statement Considered Harmful”"10. Languages since then give structured statements first, and keep goto or labeled jumps only for special cases. JavaScript, for example, "supports a compact set of statements, specifically control flow statements"11.
References
- Control flow, Wikipedia, Introduction
- Structured program theorem, Wikipedia, Introduction; Bibliography
- Control Flow, Crafting Interpreters, Robert Nystrom, 9.1 Turing Machines (Briefly); 9.2 Conditional Execution
- Statements, C reference, cppreference.com, Introduction
- Jump statements, C# language reference, Introduction
- The Java Language Specification, Java SE 25 Edition, Chapter 14, Introduction; 14.1 Normal and Abrupt Completion of Statements
- The Go Programming Language Specification, Statements; Terminating statements
- Compound statements, The Python Language Reference, Introduction
- Control Flow, The Rust Programming Language, Introduction
- A Case against the GO TO Statement (EWD215), Edsger W. Dijkstra, Introduction; transcriber's note
- Control flow and error handling, MDN Web Docs, Introduction
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 YXD2DJ Edit this page History Report an error Markdown