Programming Search⌘K

Conceptcore

Program state

Also called state, program state, state of a program, stateful, stateless, state variable, mutable state, global state, execution state, machine state.

The state of a running program is everything it remembers at one moment: the values of its variables and objects, the place it has reached in the code, and its open files.

Applies to
core-languages

Idea

A running program remembers things. At each moment it has values in its variables, objects on the heap, a call stack that records which functions are active, a position in the code that says what runs next, and resources outside memory, such as open files and network connections. All of this is the state of the program. Each step of the run reads the state and changes a part of it, so a run is a sequence of states. The same code gives a different result when it starts from a different state, and most bugs are states that the programmer did not expect.

import sys


def digit_sum(n):
    total = 0
    while n > 0:
        total += n % 10
        n //= 10
    return total


def show(frame, event, arg):  # called by Python before each line of digit_sum
    if frame.f_code is digit_sum.__code__:
        if event == "line":
            line = frame.f_lineno - digit_sum.__code__.co_firstlineno
            print(f"before line {line}: {dict(frame.f_locals)}")
        return show
    return None


sys.settrace(show)
result = digit_sum(472)
sys.settrace(None)
print("result:", result)


def counter():  # a generator keeps its local state between calls
    count = 0
    while True:
        count += 1
        yield count


c = counter()
print("next:", next(c), next(c), next(c))
print("suspended frame locals:", c.gi_frame.f_locals)
Output
before line 1: {'n': 472}
before line 2: {'n': 472, 'total': 0}
before line 3: {'n': 472, 'total': 0}
before line 4: {'n': 472, 'total': 2}
before line 2: {'n': 47, 'total': 2}
before line 3: {'n': 47, 'total': 2}
before line 4: {'n': 47, 'total': 9}
before line 2: {'n': 4, 'total': 9}
before line 3: {'n': 4, 'total': 9}
before line 4: {'n': 4, 'total': 13}
before line 2: {'n': 0, 'total': 13}
before line 5: {'n': 0, 'total': 13}
result: 13
next: 1 2 3
suspended frame locals: {'count': 3}

sys.settrace asks Python to call a function before each line, and the function prints the local variables of digit_sum at that moment. The output is the run as a sequence of states: each line reads n and total and changes one of them, until the loop condition is false. The line number is part of the state too, because the same values at a different line lead to a different next step. The generator counter shows state that outlives a call: after each yield, the frame of the function stays in memory with count in it, and the next call goes on from there.

How it works

What the state contains. At the level of the machine, the state is the contents of the registers, including the program counter, and the contents of memory. At the level of a language, it is the values of all variables that exist, the objects that they reach, the call stack with the return point of each active call, and the position in the current function. The state also includes things outside the process that the program can observe: files, the database, the environment and the clock. A debugger shows the language-level state, and Python's sys.settrace gives the same view to a program, which "allows you to implement a Python source code debugger in Python."2

State changes with time. In mathematics, a function gives the same value for the same argument. A program with state does not. Structure and Interpretation of Computer Programs says that an object has state "if its behavior is influenced by its history", and goes on: "We can characterize an object's state by one or more state variables, which among them maintain enough information about history to determine the object's current behavior."1 A bank account does not store all its deposits and withdrawals to answer "can I withdraw 100?"; it stores the balance, which summarizes the history.

Where state lives. Each kind of storage gives state a lifetime. Local variables live while their call is active. Objects on the heap live while something refers to them. Global and static variables live for the whole run; in C, static storage duration means "The storage duration is the entire execution of the program, and the value stored in the object is initialized only once, prior to main function."4 Closures keep the variables they capture alive after the enclosing call returns. Generators and iterators keep their whole frame: in Python, "Each yield temporarily suspends processing, remembering the execution state (including local variables and pending try-statements)."3 C# iterator methods also keep their locals and their position between calls,7 and the compiler turns each one into a class whose fields hold them. State that must survive the end of the process goes to files or databases, usually through serialization.

Who can change the state. The fewer places that can change a piece of state, the easier it is to know its value. Local variables can change only inside their function. Private fields can change only through the methods of their class, which can keep the state valid: a method rejects a withdrawal that would make the balance negative. Global variables and hidden static variables can change anywhere, and every function that uses them depends on the order of all calls. C's strtok is a known case: "Each call to strtok modifies a static variable: is not thread safe."5 Side effects are the operations that change state.

State machines and valid states. When an object has a few modes, such as idle, running and done, the mode is part of its state, and each event moves it to a new mode or is invalid in the current one. Code can store the mode in an enum and check each transition, or it can give each mode its own type. The Rust book shows how to "encode the states into different types", so that invalid transitions are errors when the program compiles.6 A sum type, such as a Rust enum or a C++ std::variant, stores only the data that each state needs, so a state such as "ready, but with no data" cannot exist.

Reasoning about state. To show that code is correct, a programmer states a condition on the state at a point in the code, such as "total is the sum of the digits removed so far". An invariant is a condition that holds every time the program reaches a point, such as the start of a loop or the end of each public method. Robert Floyd and Tony Hoare built proofs of programs on such conditions. Tests use the same idea: set up a state, run the code, and check the new state.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the state of JavaScript, and readonly properties and discriminated unions describe valid states when the program compiles, but no example file exists.
GoNative
RustNative
KotlinNativeKotlin has var for state that changes and val for state that does not, and sealed classes model the modes of an object, but no example file exists because kotlinc is not installed.
SQLNativeThe tables of a database are its state, and a transaction moves the database from one valid state to the next.
BashNativeThe state of a script is its shell variables, the environment, the working directory and files, and a subshell gets a copy that its changes do not leave, but no example file exists.
PowerShellNativeThe state of a script is its variables in their scopes, the environment and the current location, but no example file exists because pwsh is not installed.
HTMLIdiomThe DOM and form controls hold the state of a page, such as the text of an input and the checked state of a box.
CSSIdiomPseudo-classes such as :hover, :focus and :checked select elements by their state, but CSS does not change state.
Regular expressionsDoes not applyA pattern has no state; the matching engine keeps its own state while it runs.
Language Verdict Mechanism
Python native variables, objects, closures, generator frames
JavaScript native variables, objects, closures, generators
TypeScript native as JavaScript; readonly limits writes
Java native fields, statics, enums for modes
Kotlin native var and val, sealed classes for modes
C# native fields, statics, iterator state machines
Go native structs with methods, package variables, closures
Rust native let mut, ownership; states as types
C native automatic, static and allocated storage
C++ native objects with invariants; std::variant for modes
Bash native shell variables, the environment, files
PowerShell native variables with scopes, the environment
SQL native the tables of the database are its state
Regex n/a the engine has state; the pattern does not
HTML idiom form controls and the DOM hold state in a page
CSS idiom pseudo-classes such as :hover and :checked select by state

Every general-purpose language has mutable state, so the verdict is native for all of them. They differ in how they limit who changes it. Rust allows a change only through a mut binding or a &mut reference, and only one such reference at a time. Java, C#, C++ and Kotlin use private fields and methods that keep invariants. Go relies on unexported fields and convention. Python and JavaScript protect state mostly by convention, with closures and private fields as stronger tools. SQL keeps the state in tables and changes it in transactions, which move the database from one valid state to the next. HTML and CSS are idiom: a page has state in the DOM and in its form controls, and CSS can select elements by that state.

The example files show the kinds of state. Python keeps the state of an account valid in a method and saves it to a file. JavaScript keeps state in closures and in the position of a generator. Java checks the transitions of an enum state machine. C# shows that each enumerator of an iterator has its own state. Go copies the state of a struct to make a snapshot. Rust puts the state of a door in its type, so that the compiler rejects a wrong transition. C shows hidden static state in strtok breaking a nested loop. C++ holds one of four states in a std::variant.

PythonGitHub
import json
import os
import tempfile


class Account:
    def __init__(self, balance=0):
        self.balance = balance  # the state of the object
        self.history = []

    def withdraw(self, amount):  # the method keeps the state valid
        if amount > self.balance:
            raise ValueError(f"balance {self.balance} is less than {amount}")
        self.balance -= amount
        self.history.append(-amount)


acc = Account(100)
acc.withdraw(30)
try:
    acc.withdraw(100)
except ValueError as err:
    print("refused:", err)
print("state:", vars(acc))

path = os.path.join(tempfile.mkdtemp(), "account.json")
with open(path, "w") as f:  # state that must outlive the process goes to storage
    json.dump(vars(acc), f)
del acc
with open(path) as f:
    restored = Account()
    restored.__dict__.update(json.load(f))
print("restored:", vars(restored))
Output
refused: balance 70 is less than 100
state: {'balance': 70, 'history': [-30]}
restored: {'balance': 70, 'history': [-30]}
  • Verdict: native. The state of an object is in its attributes, which vars shows as a dictionary. Methods such as withdraw check a change before they make it, so the state stays valid, but Python does not stop other code from writing acc.balance directly; a leading underscore or a property marks the field as internal. The state in memory ends with the process, so the file saves it and a new object loads it.
#include <iostream>
#include <string>
#include <variant>

struct Idle {};
struct Loading { int percent; };
struct Ready { std::string data; };
struct Failed { std::string error; };

// The state holds exactly one of these, with only the data that the state needs.
using State = std::variant<Idle, Loading, Ready, Failed>;

std::string describe(const State& s) {
    struct Visitor {
        std::string operator()(const Idle&) const { return "idle"; }
        std::string operator()(const Loading& l) const { return "loading " + std::to_string(l.percent) + "%"; }
        std::string operator()(const Ready& r) const { return "ready: " + r.data; }
        std::string operator()(const Failed& f) const { return "failed: " + f.error; }
    };
    return std::visit(Visitor{}, s);
}

int main() {
    State s = Idle{};
    std::cout << describe(s) << '\n';
    s = Loading{40};
    std::cout << describe(s) << '\n';
    s = Ready{"42 rows"};
    std::cout << describe(s) << '\n';
    std::cout << "holds Loading? " << std::boolalpha << std::holds_alternative<Loading>(s) << '\n';
}
Output
idle
loading 40%
ready: 42 rows
holds Loading? false
  • Verdict: native. A class keeps its state in private members and keeps its invariants in its member functions. std::variant, from C++17, holds exactly one of a fixed list of types, so each state carries only its own data: a Loading state has a percentage and a Ready state has the data. std::visit calls the overload for the current state, and the compiler rejects a visitor that misses one of the types.
JavaGitHub
public class Main {
    enum State { IDLE, RUNNING, PAUSED, DONE }

    static State next(State s, String event) {
        return switch (s) {
            case IDLE -> event.equals("start") ? State.RUNNING : fail(s, event);
            case RUNNING -> switch (event) {
                case "pause" -> State.PAUSED;
                case "finish" -> State.DONE;
                default -> fail(s, event);
            };
            case PAUSED -> event.equals("resume") ? State.RUNNING : fail(s, event);
            case DONE -> fail(s, event);
        };
    }

    static State fail(State s, String event) {
        throw new IllegalStateException(event + " is not allowed in " + s);
    }

    public static void main(String[] args) {
        State s = State.IDLE;
        for (String e : new String[] {"start", "pause", "resume", "finish", "start"}) {
            try {
                State t = next(s, e);
                System.out.println(s + " --" + e + "--> " + t);
                s = t;
            } catch (IllegalStateException ex) {
                System.out.println("rejected: " + ex.getMessage());
            }
        }
    }
}
Output
IDLE --start--> RUNNING
RUNNING --pause--> PAUSED
PAUSED --resume--> RUNNING
RUNNING --finish--> DONE
rejected: start is not allowed in DONE
  • Verdict: native. An enum names the modes of an object, and a switch expression gives the next mode for each pair of mode and event. The compiler checks that the switch covers every enum constant, and the method throws IllegalStateException for an event that is not valid in the current mode. Sealed interfaces with records give each mode its own data, in the style of a sum type.
#define _POSIX_C_SOURCE 200809L /* for strtok_r */
#include <stdio.h>
#include <string.h>

int main(void) {
    char text[] = "a=1,b=2;c=3";
    char *save_outer, *save_inner;
    /* strtok_r keeps its position in a variable that the caller owns */
    for (char *rec = strtok_r(text, ";", &save_outer); rec; rec = strtok_r(NULL, ";", &save_outer)) {
        printf("record:");
        for (char *f = strtok_r(rec, ",", &save_inner); f; f = strtok_r(NULL, ",", &save_inner))
            printf(" [%s]", f);
        printf("\n");
    }
    return 0;
}
Output
record: [a=1] [b=2]
record: [c=3]

This code runs but gives a wrong answer on purpose.

#include <stdio.h>
#include <string.h>

int main(void) {
    char text[] = "a=1,b=2;c=3";
    /* strtok keeps its position in one hidden static variable */
    for (char *rec = strtok(text, ";"); rec; rec = strtok(NULL, ";")) {
        printf("record:");
        for (char *f = strtok(rec, ","); f; f = strtok(NULL, ","))
            printf(" [%s]", f);
        printf("\n");
    }
    return 0;
}
Output
record: [a=1] [b=2]
  • Verdict: native. C has three storage durations for state: automatic for locals, static for globals and static locals, and allocated for malloc. strtok_r, from POSIX, keeps its position in a pointer that the caller passes in, so two loops can tokenize at the same time. C11 has strtok_s in its optional Annex K.
  • The wrong block uses strtok, which keeps its position in one hidden static variable. The inner loop moves that position to the end of the first record, so the outer loop stops and the record c=3 is lost.
IEnumerable<int> Evens()
{
    int n = 0; // the compiler moves this local into a hidden state object
    while (true)
    {
        yield return n;
        n += 2;
    }
}

var seq = Evens();
using var e1 = seq.GetEnumerator();
using var e2 = seq.GetEnumerator();
e1.MoveNext(); e1.MoveNext(); e1.MoveNext();
e2.MoveNext();
Console.WriteLine($"e1 at {e1.Current}, e2 at {e2.Current}"); // each enumerator has its own state
Console.WriteLine(string.Join(", ", seq.Take(4)));
Output
e1 at 4, e2 at 0
0, 2, 4, 6
  • Verdict: native. The compiler turns an iterator method into a class that implements the enumerator, with fields for the local n and for the position after the last yield return. Each call of GetEnumerator makes a new object with its own state, so e1 and e2 move independently, and Take(4) starts again from 0.
JavaScriptGitHub
function makeCounter() {
  let count = 0; // lives on after makeCounter returns, in the closure
  return () => ++count;
}

const a = makeCounter();
const b = makeCounter();
console.log(a(), a(), a(), "b:", b());

function* trafficLight() { // the position in the code is part of the state
  while (true) {
    yield "green";
    yield "yellow";
    yield "red";
  }
}
const light = trafficLight();
console.log(Array.from({ length: 5 }, () => light.next().value).join(" -> "));
Output
1 2 3 b: 1
green -> yellow -> red -> green -> yellow
  • Verdict: native. A closure keeps the variables of its enclosing call alive, so each counter has its own count that no other code can reach. A generator keeps its position in the code between calls: the traffic light has no variable for the colour, because the yield where it stopped is the state. Private class fields, written #count, give the same protection to object state.
package main

import (
	"errors"
	"fmt"
)

// A Turnstile is locked until a coin arrives, and a push locks it again.
type Turnstile struct {
	locked bool
	coins  int
	passes int
}

func (t *Turnstile) Coin() {
	t.coins++
	t.locked = false
}

func (t *Turnstile) Push() error {
	if t.locked {
		return errors.New("locked: insert a coin")
	}
	t.passes++
	t.locked = true
	return nil
}

func main() {
	t := &Turnstile{locked: true}
	fmt.Println("push:", t.Push())
	t.Coin()
	fmt.Println("push:", t.Push())
	fmt.Println("push:", t.Push())
	fmt.Printf("state: %+v\n", *t)

	snapshot := *t // copying the struct copies the state
	t.Coin()
	fmt.Printf("now %+v, snapshot %+v\n", *t, snapshot)
}
Output
push: locked: insert a coin
push: <nil>
push: locked: insert a coin
state: {locked:true coins:1 passes:1}
now {locked:false coins:2 passes:1}, snapshot {locked:true coins:1 passes:1}
  • Verdict: native. The fields of a struct hold its state, and methods with a pointer receiver change it. The turnstile refuses a push while it is locked, so the state stays valid. Fields that start with a lower-case letter cannot be reached from other packages. Assigning a struct copies all its fields, so snapshot keeps the old state, but fields that are slices, maps or pointers would still share data with the original.
RustGitHub
use std::marker::PhantomData;

struct Open;
struct Closed;

// The state is a type parameter, so the compiler knows it.
struct Door<S> {
    name: String,
    state: PhantomData<S>,
}

impl Door<Closed> {
    fn new(name: &str) -> Self {
        Door { name: name.to_string(), state: PhantomData }
    }
    fn open(self) -> Door<Open> {
        println!("{} opens", self.name);
        Door { name: self.name, state: PhantomData }
    }
}

impl Door<Open> {
    fn close(self) -> Door<Closed> {
        println!("{} closes", self.name);
        Door { name: self.name, state: PhantomData }
    }
}

fn main() {
    let door = Door::new("front");
    let door = door.open();
    let door = door.close();
    let _ = door.open();
}
Output
front opens
front closes
front opens

This code does not compile, on purpose. The error is E0599.

use std::marker::PhantomData;

struct Open;
struct Closed;

struct Door<S> {
    state: PhantomData<S>,
}

impl Door<Closed> {
    fn open(self) -> Door<Open> {
        Door { state: PhantomData }
    }
}

impl Door<Open> {
    fn close(self) -> Door<Closed> {
        Door { state: PhantomData }
    }
}

fn main() {
    let door: Door<Closed> = Door { state: PhantomData };
    let door = door.close(); // close is defined only for Door<Open>
    let _ = door.open();
}
  • Verdict: native. A binding changes only when it is declared mut. The typestate idiom puts the state in a type parameter, so Door<Closed> has open and Door<Open> has close, and each transition consumes the old value and returns a new one. PhantomData marks the type parameter and takes no memory. The fails block calls close on a closed door, and the compiler reports E0599 because Door<Closed> has no such method.
  • Stateless code. A pure function or a stateless service keeps nothing between calls, so it gives the same answer for the same input and can be repeated or run in parallel.
  • Immutable state. Programs in functional style make a new state instead of changing the old one, and keep the old one for undo, history or other threads. See immutability.
  • Finite-state machines. A finite-state machine has a fixed set of states and transitions, a model for parsers, protocols and user interfaces.
  • The state pattern. The state pattern gives each state an object with its own behavior.
  • Shared state and concurrency. State that two threads can change needs locks, atomic operations or message passing.
  • Persistent state. Files, databases and caches keep state across runs; checkpoints and snapshots save the whole state so a run can restart.

Pitfalls

  • Hidden global state. Functions such as strtok, rand and setlocale keep state in static variables, so two uses interfere. Use the versions that take the state as an argument, such as strtok_r.
  • Invalid combinations. Separate flags such as loading, loaded and error allow states that make no sense, such as loading and loaded at once. Use one field for the mode, or a sum type.
  • Stale copies. A copy of the state does not follow later changes, and a reference to it follows all of them. Choose on purpose, as the Go snapshot does.
  • State that tests leak. A test that changes a global variable, an environment variable or a file can make the next test pass or fail. Reset the state, or avoid it in the code under test.
  • Order dependence. Code that works only when one function runs before another depends on state that the reader cannot see. Pass the needed values as arguments.
  • State lost at restart. State in memory is gone when the process ends or crashes. Save what must survive, and design the program to start from the saved state.

Cost

State costs memory, and each kind of storage has its cost: locals on the stack cost almost nothing, heap objects cost an allocation and later a free or a garbage collection, and state on disk costs I/O. The larger cost is in reasoning. The number of possible states grows with the product of the values of each variable, so ten independent flags give 1,024 states to test. Shared mutable state between threads costs synchronization. Copying state to keep it immutable costs time and memory, which persistent data structures reduce by sharing the unchanged parts.

History

Alan Turing's machine of 1936 made state part of the definition of computation: the machine has a finite set of internal states, and the tape holds the rest. The stored-program computers of the late 1940s, described in John von Neumann's report on the EDVAC in 1945, kept instructions and data in one memory, and a program changed that memory step by step. Assembly languages and the first high-level languages, such as FORTRAN, were built on assignment to variables.

Robert Floyd in 1967 and Tony Hoare in 1969 gave ways to prove programs correct by stating conditions on the state before and after each statement. Object-oriented languages from Simula in 1967 grouped state with the code that changes it, and Abelson and Sussman's book of 1985 made "assignment and local state" a main topic.1 Functional programming, from Lisp to Haskell, has tried to limit mutable state, and modern languages such as Rust make the rules about who changes state part of the type system.

References

  1. Harold Abelson and Gerald Jay Sussman, Structure and Interpretation of Computer Programs, second edition, MIT Press, 1996, 3.1 Assignment and Local State
  2. sys, System-specific parameters and functions, Python documentation, sys.settrace
  3. Glossary, Python documentation, generator iterator
  4. Storage-class specifiers, C reference, cppreference.com, Storage duration, static
  5. strtok, strtok_s, cppreference.com, Notes
  6. Implementing an Object-Oriented Design Pattern, The Rust Programming Language, Encoding States and Behavior as Types
  7. Iterators, C# guide, Produce elements with yield return

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