Conceptcore
Structured programming
Also called structured programming, structured control flow, goto, go to statement considered harmful, single entry single exit, labeled break.
Structured programming builds control flow from nested sequences, choices, loops and calls, each with one entry and one exit, so that the text of a program shows the order of its execution.
- Applies to
- core-languages
Idea
Structured programming builds the control flow of a program from a few nested forms, each with one entry and one exit: a sequence of statements, a choice between alternatives, a loop, and a call to a subroutine. A program that only uses these forms can be read from top to bottom, and the shape of the text shows the shape of the execution. The alternative is free jumps with goto to any label, which can make the order of execution impossible to see from the text. Today most code is structured, and most languages do not let a jump go anywhere. The idea still matters when a program must leave a loop early, handle an error, or release resources on every path:
def find(grid, target):
for r, row in enumerate(grid):
for c, value in enumerate(row):
if value == target:
return r, c
return None
grid = [[3, 1, 4], [1, 5, 9], [2, 6, 5]]
print(find(grid, 9))
print(find(grid, 7))
(1, 2)
None
The search has nested loops and two exits, but each exit is a return from the function. The reader knows that control leaves the function at that point, and that no other code can jump into the middle of the loops.
How it works
Three forms are enough. In 1966, Corrado Böhm and Giuseppe Jacopini proved that any flowchart can be rewritten with only sequence, selection and iteration. Knuth summarized the result: "Jacopini showed, in effect, that any program given, say, in flowchart form can be transformed systematically into another program, which computes the same results and which is built up from statements in the original program using only the three basic operations of composition, conditional, and iteration".1 The construction can need extra Boolean variables, so the result proves that goto is not necessary, not that the result is clearer.
Static text, dynamic process. Edsger Dijkstra gave the main argument in his 1968 letter. He wrote that "our intellectual powers are rather geared to master static relations and that our powers to visualize processes evolving in time are relatively poorly developed", and that programmers should therefore "shorten the conceptual gap between the static program and the dynamic process".2 With nested blocks, the position in the text tells where the program is in its execution. With free jumps, a reader must trace every path that can reach a label. Dijkstra concluded: "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."2
One entry, one exit. Each structured form can be treated as a single statement. A reader, a proof or a compiler can reason about a block from its start state to its end state, and then forget the inside of the block. This is the base of the stepwise refinement of a program, and of proofs with preconditions and postconditions.
Structured exits. A strict rule of one exit per block makes some code worse, for example a search that must stop on the first match. Knuth argued for a balance: "I argue for the elimination of go to's in certain cases, and for their introduction in others."1 Modern languages give restricted jumps that keep the structure: return, break and continue, labeled break for nested loops, exceptions for errors, and finally, defer and destructors for cleanup. Each of these only goes outward, to a point that the text makes clear.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | As JavaScript, with labeled break and continue and no goto. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has no goto, and labels such as break@outer leave enclosing loops; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | A query has no control flow; procedural extensions such as PL/pgSQL and T-SQL add loops and blocks. |
| Bash | Native | |
| PowerShell | Native | A label such as :outer before a loop lets break outer and continue outer leave enclosing loops; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | HTML has no statements. |
| CSS | Does not apply | CSS has no statements. |
| Regular expressions | Does not apply | A regular expression has no statements. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | blocks, break, continue, return, loop else, exceptions; no goto |
| JavaScript | native | labeled break and continue; no goto |
| TypeScript | native | as JavaScript |
| Java | native | labeled break and continue, finally; goto reserved but unused |
| Kotlin | native | labels such as break@outer; no goto |
| C# | native | goto to a label, goto case; no labeled break |
| Go | native | labeled break and continue, defer, a restricted goto |
| Rust | native | labeled loops and blocks, break with a value, ?; no goto |
| C | native | goto within a function, single-exit cleanup |
| C++ | native | goto, destructors for cleanup |
| Bash | native | break n, continue n; no goto |
| PowerShell | native | labeled loops with break label; no goto |
| SQL | n/a | no control flow in a query |
| Regex, HTML, CSS | n/a | no statements |
Python has no goto. The design FAQ states that unrestricted goto "could lead to messy “spaghetti” code that was hard to understand and revise", and that "one can also use exceptions to provide a “structured goto” that works even across function calls."3
JavaScript and TypeScript allow a label on a statement: "A labeled statement is any statement that is prefixed with an identifier. You can jump to this label using a break or continue statement nested within the labeled statement."4 Java has the same rule. A break with a label transfers control "to the enclosing labeled statement".5
Rust labels loops and blocks. "A loop expression may optionally have a label", and break can give the labeled expression a value.6
Go has a goto, but with limits. "Executing the "goto" statement must not cause any variables to come into scope that were not already in scope at the point of the goto."7 C# has goto, which "transfers control to a statement that is marked by a label", and goto case inside a switch.8
C has an unrestricted goto within one function. The Linux kernel coding style uses it for one purpose: "The goto statement comes in handy when a function exits from multiple locations and some common work such as cleanup has to be done."9 C++ has the same goto, but destructors do the cleanup on every exit, so the pattern is rarely necessary.
def first_negative(rows):
for r, row in enumerate(rows):
for c, value in enumerate(row):
if value < 0:
return r, c
return None
print(first_negative([[3, 1], [4, -1], [-5, 9]]))
for n in [9, 15, 21]:
if n % 2 == 0:
print("found an even number:", n)
break
else:
print("no even number")
(1, 1)
no even number
- Verdict: native. Python has blocks,
if,while,for,break,continue,returnand exceptions, and nogoto. The design FAQ states that exceptions can act as a structuredgotothat works across function calls. - To leave nested loops, move them into a function and
return. Theelseclause of a loop runs only when the loop ends withoutbreak.
#include <fstream>
#include <iostream>
#include <optional>
#include <utility>
#include <vector>
std::optional<std::pair<int, int>> first_negative(const std::vector<std::vector<int>>& grid) {
for (int r = 0; r < static_cast<int>(grid.size()); ++r) {
for (int c = 0; c < static_cast<int>(grid[r].size()); ++c) {
if (grid[r][c] < 0) {
return std::pair{r, c};
}
}
}
return std::nullopt;
}
bool write_squares(const char* path) {
std::ofstream file(path);
if (!file) {
return false;
}
std::vector<int> numbers;
for (int i = 0; i < 5; ++i) {
numbers.push_back(i * i);
file << numbers.back() << "\n";
}
return static_cast<bool>(file);
}
int main() {
auto found = first_negative({{3, 1}, {4, -1}, {-5, 9}});
std::cout << found->first << "," << found->second << "\n";
std::cout << std::boolalpha << write_squares("squares.txt") << " " << write_squares("no-such-dir/x") << "\n";
}
1,1
true false
- Verdict: native. C++ has the C statements, including
goto. Destructors run on every exit from a scope, so an earlyreturnreleases resources with no cleanup labels.
This code does not compile, on purpose.
#include <iostream>
#include <string>
int main(int argc, char**) {
if (argc > 5) {
goto done;
}
std::string name = "unused";
done:
std::cout << "end\n";
}
The compiler rejects the jump, because it would skip the initialization of name, and the destructor of name would then run on an object that was never made.
public class Main {
public static void main(String[] args) {
int[][] grid = {{3, 1}, {4, -1}, {-5, 9}};
int foundRow = -1;
int foundCol = -1;
search:
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] < 0) {
foundRow = r;
foundCol = c;
break search;
}
}
}
System.out.println(foundRow + "," + foundCol);
}
}
1,1
- Verdict: native.
gotois a reserved word in Java, but it has no meaning. A labeledbreakorcontinueleaves enclosing loops, andtry/finallyruns cleanup on every exit.
#include <stdio.h>
#include <stdlib.h>
static int copy_numbers(const char *path, size_t count) {
int status = -1;
int *numbers = malloc(count * sizeof *numbers);
if (numbers == NULL) {
goto out;
}
FILE *file = fopen(path, "w");
if (file == NULL) {
goto free_numbers;
}
for (size_t i = 0; i < count; i++) {
numbers[i] = (int)(i * i);
if (fprintf(file, "%d\n", numbers[i]) < 0) {
goto close_file;
}
}
status = 0;
close_file:
fclose(file);
free_numbers:
free(numbers);
out:
return status;
}
int main(void) {
printf("%d\n", copy_numbers("squares.txt", 5));
printf("%d\n", copy_numbers("no-such-dir/squares.txt", 5));
return 0;
}
0
-1
- Verdict: native. C has blocks, loops,
switch,break,continueandreturn, and it also hasgotowithin one function.breakleaves only the innermost loop orswitch. - The main accepted use of
gotois the single exit for cleanup. Each label releases one resource, in the reverse order of acquisition. The Linux kernel coding style recommends this pattern.
foreach (int code in new[] { 1, 2, 3, 4 })
{
Console.WriteLine($"{code}: {Describe(code)}");
}
static string Describe(int code)
{
string text = "";
switch (code)
{
case 1:
text += "minor ";
goto case 2;
case 2:
text += "warning";
break;
case 3:
text = "error";
break;
default:
return "unknown";
}
return text;
}
1: minor warning
2: warning
3: error
4: unknown
- Verdict: native. C# has
gototo a label,goto caseandgoto default. Aswitchsection cannot fall through to the next section, so the jump must be explicit. - C# has no labeled
break. To leave nested loops, usereturnfrom a method or a local function.
const grid = [
[3, 1],
[4, -1],
[-5, 9],
];
let found = null;
search: for (const [r, row] of grid.entries()) {
for (const [c, value] of row.entries()) {
if (value < 0) {
found = [r, c];
break search;
}
}
}
console.log(found);
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j > i) continue outer;
if (i === 2) break outer;
console.log(i, j);
}
}
[ 1, 1 ]
0 0
1 0
1 1
- Verdict: native. JavaScript has no
goto. A label on a loop or a block letsbreakandcontinueleave several levels of nesting, but only outward, and only to an enclosing statement.
package main
import "fmt"
func main() {
grid := [][]int{{3, 1}, {4, -1}, {-5, 9}}
row, col := -1, -1
search:
for r, line := range grid {
for c, value := range line {
if value < 0 {
row, col = r, c
break search
}
}
}
fmt.Println(row, col)
}
1 1
- Verdict: native. Go has labeled
breakandcontinue,deferfor cleanup, and a restrictedgoto. Agotomust not jump into a block or over a variable declaration.
This code does not compile, on purpose.
package main
import "fmt"
func main() {
goto end
message := "skipped"
fmt.Println(message)
end:
fmt.Println("end")
}
The compiler rejects the program: goto end jumps over the declaration of message.
fn main() {
let grid = [[3, 1], [4, -1], [-5, 9]];
let found = 'search: {
for (r, row) in grid.iter().enumerate() {
for (c, &value) in row.iter().enumerate() {
if value < 0 {
break 'search Some((r, c));
}
}
}
None
};
println!("{found:?}");
let mut n = 27u64;
let mut count = 0;
let steps = loop {
if n == 1 {
break count;
}
n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };
count += 1;
};
println!("{steps}");
}
Some((1, 1))
111
- Verdict: native. Rust has no
goto. Loops and blocks can have labels, andbreak 'label valueleaves a labeled block or loop with a value. loopis an expression, andbreakgives it a value.?returns early from a function with an error, andDropruns cleanup on every exit.
for r in 0 1 2; do
for c in 0 1 2; do
if (( r + c == 3 )); then
echo "found $r $c"
break 2
fi
done
done
n=0
while true; do
(( n++ ))
(( n % 2 == 0 )) && continue
(( n > 5 )) && break
echo "odd $n"
done
found 1 2
odd 1
odd 3
odd 5
- Verdict: native. Bash has
if,case,for,while,untiland functions, and nogoto.break nandcontinue nact on the nth enclosing loop.
Variations and related ideas
Procedural programming. Structured control flow inside procedures, and procedures as the unit of decomposition, together are the classic style of Pascal and C.
Exceptions. An exception is a structured non-local exit: it goes outward through calls to the nearest handler. See exception handling.
Cleanup on every path. finally, defer, with and destructors run code on every exit from a scope, which removes the main reason for goto in C. See defer and finally and RAII.
Recursion and higher-order functions. Recursion and functions such as map and filter replace many loops, and they also have one entry and one exit.
Unstructured control in a structured form. Coroutines, generators, async functions and continuations can suspend and resume a function in the middle. The compiler turns them into state machines with jumps, but the source code keeps a structured shape.
State machines. Some programs, such as lexers and protocol handlers, are naturally graphs of states. A switch in a loop, a table of states, or tail calls express them without free jumps.
Pitfalls
Flag variables. A strict rule of one exit can force a Boolean flag that each loop must test. The result is often harder to read than a return or a labeled break.
Deep nesting. Code with many nested if statements is structured, but hard to read. Early returns for error cases, called guard clauses, keep the main path at a low level of nesting.
Cleanup that a jump skips. In C, an early return from the middle of a function can skip the release of memory, locks or files. Use one exit with cleanup labels, or the defer, finally or destructor of the language.
A goto that crosses a declaration. C allows a goto that skips the initialization of a variable, and the variable then has an indeterminate value. C++ and Go reject such jumps.
Fall-through in switch. In C, C++ and Java, a case without break runs into the next case. This hidden jump causes bugs. C# forbids it, and newer languages, such as Go, Swift and Rust, do not fall through by default.
Cost
Structured control has no run-time cost. Compilers turn loops, conditionals and break into the same jumps that a goto would make. A structured program is also easier for a compiler to analyze and optimize, because its control flow graph is reducible. The cost is sometimes extra code: a flag variable, a duplicated statement or a helper function where a single jump would do.
History
Early Fortran, COBOL and assembly programs used jumps for most control flow. Algol 60 introduced nested blocks and compound statements. In 1966, Böhm and Jacopini proved that sequence, selection and iteration are enough.1 In March 1968, Communications of the ACM published Dijkstra's letter, which the editor titled "Go To Statement Considered Harmful". Dijkstra wrote that "the go to statement should be abolished from all "higher level" programming languages".2 Dijkstra, Ole-Johan Dahl and Tony Hoare published the book "Structured Programming" in 1972, and Pascal, designed by Niklaus Wirth, was built for this style. In 1974, Knuth answered the debate with "Structured Programming with go to Statements", which proposed structured exits from loops.1 Later languages took this advice: most of them have break, continue, early return and exceptions, and Java, Python, JavaScript and Rust have no goto at all.
References
- Structured Programming with go to Statements, D. E. Knuth, Computing Surveys 6(4), 1974, Introduction and Elimination of go to statements
- Go To Statement Considered Harmful, E. W. Dijkstra, Communications of the ACM 11(3), 1968, EWD 215, full letter
- Design and History FAQ, Python 3.14 documentation, Why is there no goto?
- Labeled statement, MDN Web Docs, introduction
- The Java Language Specification, Java SE 25 Edition, 14.15 The break Statement
- The Rust Reference, Loops and other breakable expressions, Rust 1.99.1, Loop labels
- The Go Programming Language Specification, Goto statements
- Jump statements, C# language reference, Microsoft Learn, The goto statement
- Linux kernel coding style, 7) Centralized exiting of functions
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 6P6Q7J Edit this page History Report an error Markdown