Programming Search⌘K

Conceptcore

Imperative programming

Also called imperative style, state and assignment, mutable state, side effects, statements, von Neumann style, assignment statement.

Imperative programming describes a computation as a sequence of statements that change the values of variables, so the program states the steps that lead to the result.

Applies to
core-languages

Idea

Imperative programming describes a computation as a sequence of commands that change the state of the program. The state is the set of current values of the variables. Each statement reads some values, computes, and stores results, and the next statement sees the changed state. The program says how to reach the result step by step, in the order the machine will do the steps:

balance = 100
history = []

for amount in [20, -50, 30, -120]:
    if balance + amount < 0:
        history.append(f"refused {amount}")
        continue
    balance += amount
    history.append(f"ok {amount}, balance {balance}")

for line in history:
    print(line)
print(balance)
Output
ok 20, balance 120
ok -50, balance 70
ok 30, balance 100
refused -120
100

The variable balance holds a different value after each pass of the loop. To know its value at one line, a reader must know which statements ran before that line. This is the main property of imperative code, and the source of both its power and its difficulty.

How it works

A model of the machine. A stored-program computer has a memory of cells and a processor that executes instructions one after another. Each instruction reads cells, computes, writes a cell, or jumps. Imperative languages give names to these operations. John Backus described the match in his Turing Award lecture: "Von Neumann programming languages use variables to imitate the computer's storage cells; control statements elaborate its jump and test instructions; and assignment statements imitate its fetching, storing, and arithmetic."1 This is why imperative code maps directly to machine code and why it was the first style of high-level language.

Variables and assignment. A variable is a named location that holds a value. Assignment changes the value. The Go specification states that "An assignment replaces the current value stored in a variable with a new value specified by an expression."2 Languages differ in what a variable holds. In C, a variable is a block of memory, and assignment copies bytes into it. In Python, Java and JavaScript, a variable of an object type holds a reference, and the Python reference says that assignment statements are used "to (re)bind names to values and to modify attributes or items of mutable objects".3 Two names can then refer to one object, and a change through one name is visible through the other. This is aliasing.

Statements and sequence. A statement is executed for its effect. The Java specification says that "The sequence of execution of a program is controlled by statements, which are executed for their effect and do not have values."4 The order of statements is part of the meaning of the program. Swapping two assignments that touch the same variable changes the result, which is not true of two independent expressions.

Control flow. Conditionals select which statements run, loops repeat statements while a condition holds, and calls run a procedure and return. Early languages used jumps to labels for all of these. Structured programming replaced free jumps with nested blocks, and most imperative code is written in that discipline today.

Procedures and side effects. A procedure can change variables that its caller can see: a global variable, an object passed by reference, or a location through a pointer. These changes are side effects. They let a procedure update a large structure in place, but they also mean that a call can change state that the call site does not name. Languages add marks to make this visible, such as ref in C#, &mut in Rust and pointer arguments in Go and C. See parameter passing.

Reasoning about state. To prove that imperative code is correct, a reader states what must be true before and after each statement. C. A. R. Hoare made this precise in 1969 with rules of the form {P} S {Q}: if P holds before statement S, then Q holds after it. A loop needs an invariant, a condition that is true before and after each pass. Informal versions of the same idea are assertions and the comments that state what a loop keeps true.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeAs JavaScript, with readonly properties and arrays checked at compile time.
GoNative
RustNative
KotlinNativeVar declares a variable that can change and val one that cannot, with for, while and do-while loops; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLIdiomA query is declarative, but INSERT, UPDATE and DELETE change stored tables in sequence, and procedural extensions such as PL/pgSQL and T-SQL add variables and loops.
BashNative
PowerShellNativeA script is a sequence of statements with variables, assignment, loops and conditionals; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML describes a document and has no statements.
CSSDoes not applyCSS declares styles and has no statements.
Regular expressionsDoes not applyA regular expression describes text and has no state or statements.
Language Verdict Mechanism
Python native assignment binds names; mutable lists, dicts and objects; +=
JavaScript native let and const, loops, destructuring assignment
TypeScript native as JavaScript, with readonly checked at compile time
Java native statements, assignment, arrays; references to objects
Kotlin native var and val, loops
C# native assignment, loops, ref and out parameters
Go native assignment, tuple assignment, one for loop, pointers
Rust native let mut to opt in to change, &mut references
C native variables as memory, pointers, statements in sequence
C++ native the statements of C, references, const
Bash native commands in sequence, global variables by default
PowerShell native statements, variables, loops
SQL idiom UPDATE, INSERT, DELETE; procedural extensions
Regex, HTML, CSS n/a no state or statements

Almost every general-purpose language is imperative at its base. The differences are in how much change each language allows by default and how visible it is. C and C++ allow any variable to change unless it is marked const. Java and C# make every local variable and field mutable unless it is marked final or readonly. Rust reverses the default. Its book says that "by default, variables are immutable", and a variable that changes must be declared let mut.5 The compiler also refuses to let two parts of a program change one value at the same time, which removes most of the risks of aliasing.

C is the most direct form. cppreference describes C statements as "fragments of the C program that are executed in sequence",6 and a pointer gives code the address of any variable. Python, JavaScript and Java hide addresses but keep shared mutable objects, so aliasing is still possible through references. Go has pointers but no pointer arithmetic, and its slices share their arrays, so a function that receives a slice can change the elements of its caller.

PythonGitHub
def reverse_in_place(xs):
    i, j = 0, len(xs) - 1
    while i < j:
        xs[i], xs[j] = xs[j], xs[i]
        i += 1
        j -= 1


data = [1, 2, 3, 4, 5]
reverse_in_place(data)
print(data)

count = 0
for ch in "imperative":
    if ch in "aeiou":
        count += 1
print(count)
Output
[5, 4, 3, 2, 1]
5

This code runs but gives a wrong answer on purpose.

grid = [[0] * 3] * 2
grid[0][0] = 9
print(grid)

a = [1, 2]
b = a
b.append(3)
print(a)
Output
[[9, 0, 0], [9, 0, 0]]
[1, 2, 3]
  • Verdict: native. Python has assignment, augmented assignment such as +=, while and for loops, and mutable lists, dictionaries and objects. The reference states that assignment statements "are used to (re)bind names to values and to modify attributes or items of mutable objects".
  • A variable names an object, and assignment binds the name. It does not copy the object.
  • In the wrong block, [[0] * 3] * 2 makes a list that holds the same inner list twice, and b = a makes a second name for one list. A change through one name shows through the other. Use [[0] * 3 for _ in range(2)] and list(a) to make copies.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

void add_to(int& total, int amount) { total += amount; }

int main() {
    std::vector<int> data{1, 2, 3, 4, 5};
    for (std::size_t i = 0, j = data.size() - 1; i < j; ++i, --j) {
        std::swap(data[i], data[j]);
    }
    for (int x : data) std::cout << x << " ";
    std::cout << "\n";

    int total = 0;
    add_to(total, 5);
    add_to(total, 7);
    std::cout << total << "\n";

    std::string word = "imperative";
    auto count = std::count_if(word.begin(), word.end(),
                               [](char c) { return std::string("aeiou").find(c) != std::string::npos; });
    std::cout << count << "\n";
}
Output
5 4 3 2 1 
12
5
  • Verdict: native. C++ has the statements of C, references that act as other names for variables, and const to mark what must not change.
  • A non-const reference parameter such as int& total lets the function change the variable of its caller, but the call add_to(total, 5) does not show this. Some style guides prefer pointers or return values for this reason.
JavaGitHub
import java.util.Arrays;

public class Main {
    static void reverseInPlace(int[] xs) {
        for (int i = 0, j = xs.length - 1; i < j; i++, j--) {
            int t = xs[i];
            xs[i] = xs[j];
            xs[j] = t;
        }
    }

    public static void main(String[] args) {
        int[] data = {1, 2, 3, 4, 5};
        reverseInPlace(data);
        System.out.println(Arrays.toString(data));

        int count = 0;
        for (char ch : "imperative".toCharArray()) {
            if ("aeiou".indexOf(ch) >= 0) {
                count++;
            }
        }
        System.out.println(count);

        StringBuilder sb = new StringBuilder();
        for (int i = 3; i > 0; i--) {
            sb.append(i).append(' ');
        }
        System.out.println(sb.append("go"));
    }
}
Output
[5, 4, 3, 2, 1]
5
3 2 1 go
  • Verdict: native. The Java specification says that "The sequence of execution of a program is controlled by statements, which are executed for their effect and do not have values."
  • A method receives a copy of a reference to the array, so it can change the elements of the array of the caller. final stops reassignment of a variable, not changes to the object.
#include <stdio.h>
#include <string.h>

static void reverse_in_place(int *xs, size_t n)
{
    if (n == 0)
        return;
    for (size_t i = 0, j = n - 1; i < j; i++, j--) {
        int t = xs[i];
        xs[i] = xs[j];
        xs[j] = t;
    }
}

static void add_to(int *total, int amount)
{
    *total += amount;
}

int main(void)
{
    int data[] = { 1, 2, 3, 4, 5 };
    reverse_in_place(data, 5);
    for (int i = 0; i < 5; i++)
        printf("%d ", data[i]);
    printf("\n");

    int total = 0;
    add_to(&total, 5);
    add_to(&total, 7);
    printf("%d\n", total);

    int count = 0;
    for (const char *p = "imperative"; *p; p++)
        if (strchr("aeiou", *p))
            count++;
    printf("%d\n", count);
    return 0;
}
Output
5 4 3 2 1 
12
5
  • Verdict: native. C is close to the machine: a variable is a named piece of memory, and a pointer is its address. cppreference describes statements as "fragments of the C program that are executed in sequence".
  • The n == 0 check matters. With size_t, n - 1 for an empty array wraps to the largest value.
int[] data = { 1, 2, 3, 4, 5 };
for (int i = 0, j = data.Length - 1; i < j; i++, j--)
{
    (data[i], data[j]) = (data[j], data[i]);
}
Console.WriteLine(string.Join(",", data));

int total = 0;
AddTo(ref total, 5);
AddTo(ref total, 7);
Console.WriteLine(total);

int count = 0;
foreach (var ch in "imperative")
{
    if ("aeiou".Contains(ch)) count++;
}
Console.WriteLine(count);

static void AddTo(ref int target, int amount) => target += amount;
Output
5,4,3,2,1
12
5
  • Verdict: native. C# has assignment, compound assignment, for, foreach, while and do, and tuple assignment swaps values.
  • A ref parameter lets a method assign to a variable of its caller. The call site must also write ref, so the reader can see that the variable may change.
JavaScriptGitHub
function reverseInPlace(xs) {
  for (let i = 0, j = xs.length - 1; i < j; i++, j--) {
    [xs[i], xs[j]] = [xs[j], xs[i]];
  }
}

const data = [1, 2, 3, 4, 5];
reverseInPlace(data);
console.log(data);

let count = 0;
for (const ch of "imperative") {
  if ("aeiou".includes(ch)) count += 1;
}
console.log(count);

const fixed = 1;
try {
  fixed = 2;
} catch (e) {
  console.log(e.name);
}
Output
[ 5, 4, 3, 2, 1 ]
5
TypeError
  • Verdict: native. JavaScript has let for variables that change and const for bindings that do not. A const binding can still refer to an object or array that changes, as data does here.
  • Loops include for, for...of, while and do...while, and destructuring assignment swaps two values in one statement.
package main

import "fmt"

func reverseInPlace(xs []int) {
	for i, j := 0, len(xs)-1; i < j; i, j = i+1, j-1 {
		xs[i], xs[j] = xs[j], xs[i]
	}
}

func addTo(total *int, amount int) {
	*total += amount
}

func main() {
	data := []int{1, 2, 3, 4, 5}
	reverseInPlace(data)
	fmt.Println(data)

	total := 0
	addTo(&total, 5)
	addTo(&total, 7)
	fmt.Println(total)

	count := 0
	for _, ch := range "imperative" {
		switch ch {
		case 'a', 'e', 'i', 'o', 'u':
			count++
		}
	}
	fmt.Println(count)
}
Output
[5 4 3 2 1]
12
5
  • Verdict: native. The Go specification says that "An assignment replaces the current value stored in a variable with a new value specified by an expression." Go has one loop keyword, for, and tuple assignment.
  • A slice shares its array with the caller, so reverseInPlace changes data. To change an integer of the caller, the function takes a pointer.
RustGitHub
fn reverse_in_place(xs: &mut [i32]) {
    let (mut i, mut j) = (0, xs.len() - 1);
    while i < j {
        xs.swap(i, j);
        i += 1;
        j -= 1;
    }
}

fn add_to(total: &mut i32, amount: i32) {
    *total += amount;
}

fn main() {
    let mut data = [1, 2, 3, 4, 5];
    reverse_in_place(&mut data);
    println!("{data:?}");

    let mut total = 0;
    add_to(&mut total, 5);
    add_to(&mut total, 7);
    println!("{total}");

    let mut count = 0;
    for ch in "imperative".chars() {
        if "aeiou".contains(ch) {
            count += 1;
        }
    }
    println!("{count}");
}
Output
[5, 4, 3, 2, 1]
12
5

This code does not compile, on purpose.

fn main() {
    let count = 0;
    count += 1;
    println!("{count}");
}
  • Verdict: native. The Rust book says that "by default, variables are immutable", and let mut opts in to change. A function that changes a value of its caller takes a &mut reference, and the caller writes &mut too.
  • The failing block assigns to a variable that is not mut, and the compiler rejects it with error E0384.
BashGitHub
data=(1 2 3 4 5)
i=0
j=$(( ${#data[@]} - 1 ))
while (( i < j )); do
    t=${data[i]}
    data[i]=${data[j]}
    data[j]=$t
    (( i++, j-- ))
done
echo "${data[@]}"

count=0
word=imperative
for (( k = 0; k < ${#word}; k++ )); do
    case ${word:k:1} in
        [aeiou]) (( count++ )) ;;
    esac
done
echo "$count"
Output
5 4 3 2 1
5
  • Verdict: native. A shell script is a sequence of commands with variables, loops and conditionals. Variables are global unless a function declares them local.
  • Procedural programming. Imperative code organized into procedures that each do one task, as in C, Pascal and Fortran.
  • Object-oriented programming. Imperative code in which the state is divided among objects, and each object changes only its own state. See object-oriented programming.
  • Declarative programming. The program states what result is wanted, not the steps. SQL queries, regular expressions and HTML are declarative. See also functional programming.
  • Local mutation inside a pure interface. A function can use loops and assignment inside, but take inputs and return a result with no other effect. Functional languages often allow this, for example with the ST monad in Haskell.
  • Concurrent state. When several threads change shared variables, the order of their statements is no longer fixed. See data races and mutual exclusion.

Pitfalls

  • Aliasing. Two names for one mutable object make a change in one place appear in another. In Python, [[0] * 3] * 2 holds the same inner list twice.
  • Hidden side effects. A function that changes a global variable or an argument makes its call sites hard to understand and its results depend on call order. Prefer return values, and make changes visible at the call site.
  • Uninitialized variables. In C and C++, reading a local variable before assignment is undefined behavior. See undefined behavior.
  • Off-by-one errors. Loops with index variables can run one time too many or too few. With an unsigned index, n - 1 for an empty array wraps around to a large number.
  • Changing a collection while iterating over it. Many languages raise an error or skip elements when a loop adds to or removes from the collection that it walks.
  • Order dependence. Statements that look independent may share state, so a reordering for clarity can change the result.

Cost

Imperative code is the closest to the machine, so it usually has the most direct cost model. An assignment to a local variable is often a register move, and an in-place update of an array writes one memory cell and allocates nothing. For large data, an in-place change avoids the copy that an immutable update needs. The costs come in other forms. Shared mutable state needs locks or atomic operations when threads use it, and the compiler must assume that a store through one pointer can change the value behind another pointer, which blocks some optimizations. C's restrict and Rust's borrow rules give the compiler the guarantee that two references do not overlap.

History

The first programs were imperative because the machines were. The stored-program design of the 1940s put code and data in one memory and executed instructions in sequence. Assembly languages named the instructions, and Fortran in 1957 let programmers write assignments and loops as formulas. ALGOL 60 added block structure and recursion, and its descendants Pascal and C carried the style to most programmers. Backus, who led the design of Fortran, later argued that these languages were limited by their match to the machine, and he called the assignment statement "the von Neumann bottleneck of programming languages".1 Since then, most new languages have stayed imperative at their base but have added limits on change: const and final, immutable strings, immutable records, and in Rust, immutable variables by default.

References

  1. Can Programming Be Liberated from the von Neumann Style? A Functional Style and Its Algebra of Programs, John Backus, Communications of the ACM 21(8), 1978, 3 Von Neumann Computers; 4 Von Neumann Languages
  2. The Go Programming Language Specification, Assignment statements
  3. The Python Language Reference, 7. Simple statements, Python 3.14 documentation, 7.2 Assignment statements
  4. The Java Language Specification, Java SE 25 Edition, Chapter 14 Blocks, Statements, and Patterns
  5. The Rust Programming Language, Variables and Mutability, Rust 1.99.1, Variables and Mutability
  6. Statements, C reference, cppreference.com, 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.

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