Conceptadvanced
Single assignment
Also called single assignment, single-assignment variable, assign once, immutable variable, immutable binding, write once variable, final variable, val, rebinding, shadowing, static single assignment, SSA.
With single assignment, a variable gets a value once and keeps it. Erlang allows only single assignment, other languages offer it with const, final or let, and compilers use it in SSA form.
- Applies to
- core-languages
Idea
In most languages, a Variable can get a new value at any time. With single assignment, it gets one value and keeps it. Wikipedia says that single assignment is "more commonly known as initialization"1, and that it "can only be done once, usually when the variable is created; no subsequent reassignment is allowed"1.
A loop that adds to a total assigns total many times. The same computation with single assignment gives each step a new name:
total = 0
for price in [3, 4, 5]:
total = total + price
print(total)
prices = [3, 4, 5]
subtotal = sum(prices)
tax = subtotal * 0.25
grand_total = subtotal + tax
print(subtotal, tax, grand_total)
12
12 3.0 15.0
In the second part, each name has one value for its whole life. A reader who sees tax anywhere knows its value without a search for other assignments.
How it works
Why it helps. A name with one value is a fact: the reader, the compiler and other threads can rely on it. An Assignment that changes a value has an effect that other code can see. "Imperative assignment can introduce side effects while destroying and making the old value unavailable while substituting it with a new one"1. Java says of final: "Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors."2
Languages with only single assignment. In Erlang, "Variables are bound to values using pattern matching. Erlang uses single assignment, that is, a variable can only be bound once."3 A second match of X = 2 after X = 1 fails. "Single assignment is the only form of assignment available in purely functional languages, such as Haskell"1. A loop in these languages is a recursive function, and each call binds the names again with new values.
Languages with both. Most languages have a keyword for a name that is assigned once: const in JavaScript, final in Java, val in Kotlin and Scala, and let without mut in Rust. In Rust it is the default: "by default, variables are immutable"4. In Java, "A final variable may only be assigned to once."2 The rule is about the name, not about the object: for JavaScript const, "The value of a constant can't be changed through reassignment using the assignment operator, but if a constant is an object, its properties can be added, updated, or removed."5 See Immutability for objects that do not change.
Rebinding is not mutation. Some languages allow a new variable with the same name. In Rust, a second let x makes a new variable that hides the first, called shadowing. "Shadowing is different from marking a variable as mut because we’ll get a compile-time error if we accidentally try to reassign to this variable without using the let keyword."4 Each x is still assigned once. Code that held the old value sees the old value.
Static single assignment in compilers. Compilers convert code to a form where each variable gets one value. "In compiler design, static single assignment form (often abbreviated as SSA form or simply SSA) is a type of intermediate representation (IR) where each variable is assigned exactly once."6 The compiler gives each assignment a new version of the name, such as x1 and x2. Where two paths join, "a special statement is inserted in the last block, called a Φ (Phi) function"6, which picks the version from the path that ran. "SSA makes numerous analyses needed for optimizations easier to perform, such as determining use-define chains, because when looking at a use of a variable there is only one place where that variable may have received a value."6
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | |
| Java | Native | |
| C | Idiom | |
| C# | Idiom | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the const of JavaScript, and readonly properties that the compiler checks. No example file exists. |
| Go | Absent | |
| Rust | Native | |
| Kotlin | Native | Val declares a name that is assigned once, and the compiler rejects a second assignment. No example file exists because kotlinc is not installed. |
| SQL | Native | A query has no variables that change. Each name of a common table expression in a WITH clause is defined once. No example file exists. |
| Bash | Idiom | Readonly NAME=value, or declare -r NAME=value, makes a variable that cannot get a new value. No example file exists. |
| PowerShell | Idiom | Set-Variable with the option ReadOnly or Constant makes a variable that cannot get a new value. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup, with no variables. |
| CSS | Does not apply | A custom property can get a new value in each rule, and the cascade picks one. |
| Regular expressions | Does not apply | A pattern has no variables. |
| Language | Verdict | Single assignment |
|---|---|---|
| Python | idiom | no single-assignment variables; typing.Final for a type checker, and tuples and frozen dataclasses for values that do not change |
| JavaScript | native | const |
| TypeScript | native | const, and readonly for properties |
| Java | native | final variables; a local variable that is never assigned again is effectively final |
| Kotlin | native | val |
| C# | idiom | readonly fields and init properties; no single-assignment local variables except const |
| Go | absent | const for compile-time values only; each variable can be assigned again |
| Rust | native | let without mut is the default, and shadowing makes a new variable |
| C | idiom | a local variable with const and an initializer |
| C++ | idiom | const and constexpr variables |
| Bash | idiom | readonly and declare -r |
| PowerShell | idiom | Set-Variable -Option ReadOnly or Constant |
| SQL | native | a query has no variables; each name in a common table expression is defined once |
| Regex | n/a | a pattern has no variables |
| HTML | n/a | HTML is markup, with no variables |
| CSS | n/a | a custom property can get a new value in each rule |
point = (1, 2)
alias = point
point = (point[0] + 1, point[1])
print(alias, point)
items = [1, 2]
same = items
items.append(3)
print(same)
(1, 2) (2, 2)
[1, 2, 3]
- Verdict: idiom. Python has no single-assignment variables, but a program can keep to them. The assignment to
pointbinds the name to a new tuple, andaliasstill has the old tuple.items.append(3)changes the list in place, sosamesees the change. Tuples, strings and frozen dataclasses cannot change, so a new value always means a new binding.
#include <iostream>
#include <string>
int main() {
const int n = 7;
const std::string kind = [&] {
if (n % 2 == 0) {
return std::string("even");
}
return std::string("odd");
}();
std::cout << n << ' ' << kind << '\n';
}
7 odd
- Verdict: idiom. A
constvariable gets its value once, in the initializer. When the value needs anifor a loop, a lambda that the program calls at once computes it, so the variable can still beconstinstead of a variable that the code assigns in two branches.
import java.util.List;
public class Main {
public static void main(String[] args) {
final int base = 10;
int offset = 5;
List<Integer> out = List.of(1, 2, 3).stream().map(x -> x * base + offset).toList();
System.out.println(out);
final String size;
if (args.length == 0) {
size = "none";
} else {
size = "some";
}
System.out.println(size);
}
}
[15, 25, 35]
none
- Verdict: native. A
finalvariable can be assigned once, and the compiler rejects a second assignment. A lambda can use only final or effectively final local variables:offsetis never assigned again, so it is effectively final. Afinalvariable can get its value later, once on each path.
#include <stdio.h>
static int square(int n) {
return n * n;
}
int main(void) {
const int base = 10;
const int doubled = base * 2;
const int area = square(doubled);
const char *const name = "Ada";
printf("%d %d %d %s\n", base, doubled, area, name);
return 0;
}
10 20 400 Ada
- Verdict: idiom. A local variable with
constmust get its value in the initializer, and the compiler rejects a later assignment. The value can come from a call at run time, asareadoes. For a pointer,const char *constmakes both the pointer and the characters constant.
using System;
var p = new Point(1, 2);
var q = p with { X = 5 };
Console.WriteLine($"{p} {q}");
var total = 0;
total += 3;
Console.WriteLine(total);
record Point(int X, int Y);
Point { X = 1, Y = 2 } Point { X = 5, Y = 2 }
3
- Verdict: idiom. C# local variables can always get a new value, except
constfor compile-time constants. Single assignment applies to data: a positional record hasinitproperties, which get a value only when the object is made, andwithmakes a copy with some properties changed.readonlyfields can be assigned only in a constructor.
const prices = [3, 4, 5];
const total = prices.reduce((sum, p) => sum + p, 0);
const label = total > 10 ? "big" : "small";
console.log(total, label);
const handlers = [];
for (let i = 0; i < 3; i++) {
handlers.push(() => i);
}
console.log(handlers.map((h) => h()));
12 big
[ 0, 1, 2 ]
- Verdict: native.
constnames get one value.reducereplaces a loop that changes a total, and the conditional operator replaces anifthat assignslabelin two places. Aletin aforloop makes a new variable on each pass, so each function keeps its owni.
package main
import "fmt"
func main() {
x := 1
if x > 0 {
x := 2
fmt.Println(x)
}
fmt.Println(x)
x = 3
fmt.Println(x)
}
2
1
3
- Verdict: absent. Go has no variable that the compiler limits to one assignment.
constworks only for values that the compiler knows.x := 2in the inner block makes a new variable that hides the outer one, and the outerxkeeps 1. The assignmentx = 3then changes the outer variable.
fn main() {
let x = 5;
let x = x + 1;
{
let x = x * 2;
println!("{x}");
}
println!("{x}");
let spaces = " ";
let spaces = spaces.len();
println!("{spaces}");
}
12
6
3
- Verdict: native. A
letvariable is immutable unless it hasmut, and an assignment to it does not compile. Shadowing makes a new variable with the same name, so eachxis assigned once. The new variable can have another type: the secondspacesis a number.
Variations and related ideas
- Erlang and equal values. Wikipedia lists "Erlang (it accepts multiple assignment if the values are equal, in contrast to Haskell)"1:
X = 1afterX = 1is a successful match. - Effectively final. Java treats a local variable that the program never assigns again as final when a lambda uses it.
- Dataflow variables. Some languages have variables that start with no value and get one value later, and a read waits for the value.
- Recursion instead of a loop. With single assignment, the state of a loop moves into the parameters of a recursive function or into a fold such as
reduce.
Pitfalls
- One variable for many values. A closure that uses a loop variable sees the variable, not its value at the time. In Python, the loop assigns
iagain on each pass, so all the functions see the last value:
This code runs but gives a wrong answer on purpose.
funcs = []
for i in range(3):
funcs.append(lambda: i)
print([f() for f in funcs])
[2, 2, 2]
Bind the value as a parameter, lambda i=i: i, so that each function gets its own name with one value. JavaScript let in a for loop makes a new variable on each pass for the same reason.
- A constant name with an object that changes.
final List<String> namescannot get a new list, butnames.add(...)changes the list. - Shadowing that hides a bug. A new variable with the same name in an inner block can hide the outer one, and an assignment meant for the outer variable changes the inner one.
Cost
Single assignment costs nothing at run time: the check is in the compiler. Code that makes a new value for each step, instead of a change in place, can cost more memory and time, for example a new list on each pass of a loop. Compilers remove much of this cost, and SSA form helps them do it.
History
Erlang and the purely functional languages made single assignment the only form. SSA form is an intermediate representation in "most high-quality optimizing compilers for imperative languages, including LLVM, the GNU Compiler Collection, and many commercial compilers"6. Newer languages make the single-assignment name the short default, such as let in Rust and val in Kotlin.
References
- Assignment (computer science), Wikipedia, Single assignment
- Chapter 4, Types, Values, and Variables, The Java Language Specification, Java SE 25, 4.12.4 final Variables
- Expressions, Erlang System Documentation, Variables
- Variables and Mutability, The Rust Programming Language, Introduction; Shadowing
- const, MDN Web Docs, Introduction
- Static single-assignment form, Wikipedia, Introduction; Converting to SSA
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 10A3P5 Edit this page History Report an error Markdown