Conceptintro
Assignment
Also called assignment, assignment statement, assignment expression, assignment operator, =, :=, reassignment, chained assignment, multiple assignment, parallel assignment, destructive assignment, augmented assignment.
Assignment gives a variable a new value: the program computes the expression on the right and stores the result in the place on the left. In some languages an assignment is also an expression.
- Applies to
- core-languages
Idea
A program that counts, sums or keeps a state must change the value of a variable. Assignment does this. "In computer programming, an assignment statement sets and/or re-sets the value stored in the storage location(s) denoted by a variable name; in other words, it copies a value into the variable."1
In Python, the statement total = total + price reads the old value of total, adds the price, and stores the sum in total:
total = 0
for price in [3, 4, 5]:
total = total + price
print(total)
total += 10
print(total)
3
7
12
22
total = total + price is not an equation, which would be false. It is an order: compute the right side, then put the value in the left side.
How it works
Two steps. "The expression is evaluated in the current state of the program. The variable is assigned the computed value, replacing the prior value of that variable."1 The left side must name a place that can change: a variable, an element of an array or a field of an object. "For an assignment operation, it is necessary that the value of the expression is well-defined (it is a valid rvalue) and that the variable represents a modifiable entity (it is a valid modifiable (non-const) lvalue)."1
Copy or rebind. In C, Go, Java and C#, assignment copies the value into the box of the variable. For a reference type, the value is a reference, so the object is not copied. In Python, "Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects"2: x = y makes the name x refer to the object of y.
Statement or expression. "In some languages, the symbol used is regarded as an operator (meaning that the assignment statement as a whole returns a value). Other languages define assignment as a statement (meaning that it cannot be used in an expression)."1 In C, C++, Java, C# and JavaScript, x = 5 is an expression. In Java, "the result of the assignment expression is the value of the variable after the assignment has occurred"3. In Python and Go, assignment is a statement, and if x = 5: is a syntax error. For an assignment inside an expression, Python has the separate operator :=: "An assignment expression (sometimes also called a “named expression” or “walrus”) assigns an expression to an identifier, while also returning the value of the expression."4
Chained assignment. "A statement like w = x = y = z is called a chained assignment in which the value of z is assigned to multiple variables w, x, and y."1 In C, the chain works because each assignment is an expression with a value, and the operator groups from the right. In Python, a = b = 0 is one statement with two targets, and the statement "assigns the single resulting object to each of the target lists, from left to right"2.
Parallel assignment. Python, Go, JavaScript and others assign several variables in one statement: a, b = 0, 1. All the values on the right are computed before any variable changes, so "a, b := b, a swaps the values of a and b"1. In Go, "The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order."5
Augmented assignment. x += 1 is a short form of x = x + 1. In Python, "Augmented assignment is the combination, in a single statement, of a binary operation and an assignment statement"2.
Assignment changes the meaning of a program. Without assignment, a name stands for one value, and an expression gives the same result each time. With assignment, the order of the steps matters. SICP: "Our programming language can no longer be interpreted in terms of the substitution model of procedure application"6. "Referential transparency is violated when we include set! in our computer language."6
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the assignment expressions and destructuring assignments of JavaScript, and checks that the type of the value fits the type of the variable. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | In Kotlin, x = e is a statement and not an expression, so it cannot be a condition. Only a var can be assigned; a val is assigned once. No example file exists because kotlinc is not installed. |
| SQL | Native | UPDATE with SET column = expression changes the values of stored rows, and procedural extensions of database systems have SET for local variables. No example file exists. |
| Bash | Native | Name=value assigns a string, with no spaces around the sign. Arithmetic assignment works inside (( )), as in (( n = n + 1 )). No example file exists. |
| PowerShell | Native | $x = e assigns any value, and $a, $b = $b, $a assigns several variables at once. An assignment in parentheses also gives its value. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup, with no assignment. |
| CSS | Idiom | A declaration such as color set to red gives a property a value, and the cascade picks one value when many rules set the same property. No example file exists. |
| Regular expressions | Does not apply | A pattern has no variables to assign. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | the statement x = e, also a, b = b, a and a = b = 0; the expression (x := e) |
| JavaScript | native | the expression x = e, with destructuring [a, b] = [b, a] |
| TypeScript | native | as JavaScript, with a type check of the value |
| Java | native | the expression x = e, whose value is the new value of x |
| Kotlin | native | the statement x = e; an assignment is not an expression |
| C# | native | the expression x = e, and tuple assignment (a, b) = (b, a) |
| Go | native | the statement x = e, also a, b = b, a; := declares and assigns |
| Rust | native | the expression x = e of type (), for a let mut variable; (a, b) = (b, a) |
| C | native | the expression x = e, whose value is the new value of x |
| C++ | native | as C, and operator= for class types |
| Bash | native | name=value with no spaces around =; (( x = x + 1 )) for arithmetic |
| PowerShell | native | $x = e, and $a, $b = $b, $a |
| SQL | native | UPDATE ... SET column = expression changes stored rows; procedural extensions have SET for variables |
| Regex | n/a | a pattern has no variables to assign |
| HTML | n/a | HTML is markup, with no assignment |
| CSS | idiom | a declaration such as color: red sets a property; the cascade picks one value from many declarations |
Go. Both phases matter when the left side reads a variable that the same statement changes: in i, x[i] = 1, 2, Go computes the index i in the first phase, so the statement sets x[0].
a = b = 0
a, b = 1, 2
a, b = b, a
print(a, b)
xs = ys = []
xs.append(1)
print(ys)
words = ["tea", "milk", "coffee"]
if (n := len(words)) > 2:
print(n)
2 1
[1]
3
- Verdict: native.
=is a statement, and one statement can have many targets, as ina = b = 0, or a tuple of targets, as ina, b = b, a. All targets ofxs = ys = []get the same list.:=is an assignment expression, with a value, so it can sit in the condition of anif.
#include <iostream>
#include <string>
#include <utility>
int main() {
std::string a = "left";
std::string b = "right";
std::string c;
c = a = b;
std::cout << a << ' ' << c << '\n';
std::pair<int, int> p{1, 2};
p = {p.second, p.first};
std::cout << p.first << ' ' << p.second << '\n';
}
right right
2 1
- Verdict: native. As in C,
=is an expression and chains from the right. For a class type such asstd::string,=calls the assignment operator of the class, which copies the characters. The braces on the right ofp = {...}build a new pair from the old values before the assignment.
public class Main {
public static void main(String[] args) {
int a, b, c;
a = b = c = 7;
System.out.println(a + b + c);
int n;
System.out.println((n = 4) * 10);
int[] xs = {0, 0};
int i = 0;
xs[i] = i = 1;
System.out.println(xs[0] + " " + xs[1] + " " + i);
}
}
21
40
1 0 1
- Verdict: native. An assignment is an expression whose value is the new value of the variable, so assignments chain from the right. Java evaluates the left operand of
=first: inxs[i] = i = 1, the indexiis still 0 when Java computes the place, so the statement setsxs[0].
#include <stdio.h>
int main(void) {
int a, b, c;
a = b = c = 5;
printf("%d\n", a + b + c);
int ch;
const char *text = "hi";
int i = 0;
while ((ch = text[i]) != '\0') {
printf("%c", ch - 32);
i += 1;
}
printf("\n");
return 0;
}
15
HI
- Verdict: native. An assignment is an expression whose value is the new value of the left side, so assignments chain, and a loop can assign and test in one condition. The parentheses around
ch = text[i]are needed, because!=binds tighter than=.
using System;
int a, b;
a = b = 3;
(a, b) = (1, 2);
(a, b) = (b, a);
Console.WriteLine($"{a} {b}");
var point = (X: 4, Y: 5);
point.X += 10;
Console.WriteLine(point);
2 1
(14, 5)
- Verdict: native.
=is an expression, as in C, so it chains. A tuple on the left takes the parts of a tuple on the right, and(a, b) = (b, a)swaps two variables.+=is a compound assignment.
let a, b;
a = b = 5;
console.log(a, b);
[a, b] = [1, 2];
[a, b] = [b, a];
console.log(a, b);
let n;
console.log((n = 3) * 2, n);
5 5
2 1
6 3
- Verdict: native.
=is an expression, and its value is the value that it assigns, soa = b = 5works from the right and(n = 3) * 2is 6. A destructuring assignment such as[a, b] = [b, a]builds the array on the right first, so it swaps the values.
package main
import "fmt"
func main() {
a, b := 1, 2
a, b = b, a
fmt.Println(a, b)
x := []int{0, 1}
i := 0
i, x[i] = 1, 2
fmt.Println(x, i)
_, err := fmt.Sscan("12", &a)
fmt.Println(a, err)
}
2 1
[2 1] 1
12 <nil>
- Verdict: native. Assignment is a statement, so
if x = 0does not compile.:=declares and assigns, and=assigns to variables that exist. A tuple assignment computes the indexes and the values first and then assigns, soi, x[i] = 1, 2setsx[0]. The blank identifier_drops a value.
fn main() {
let mut a = 1;
let mut b = 2;
(a, b) = (b, a);
println!("{a} {b}");
let unit = a = 10;
println!("{a} {unit:?}");
let mut total = 0;
for n in [3, 4, 5] {
total += n;
}
println!("{total}");
}
2 1
10 ()
12
- Verdict: native. Only a
let mutvariable can be assigned. An assignment is an expression of the unit type():let unit = a = 10setsato 10, andunitgets the value(). Soa = b = 0does not compile for numbers, andif a = 0is a type error. A tuple on the left takes the parts of a tuple on the right.
Variations and related ideas
- Initialization. The first value of a variable, given in the declaration, is its Initialization. In C++,
int x = 5;is an initialization andx = 5;is an assignment. - Single assignment. "In functional programming, assignment is discouraged in favor of single assignment, more commonly known as initialization."1 A name gets one value and keeps it. See Constant.
- Destructuring. A tuple, an array or an object on the right can fill several names on the left:
a, b = point. In the words of Wikipedia, "If the right-hand side of the assignment is a single variable (e.g. an array or structure), the feature is called unpacking"1 or destructuring assignment. - Notation. The most common notation is
x = expr, "originally Superplan 1949–51, popularized by Fortran 1957 and C"1. The second isx := expr, "originally ALGOL 1958, popularised by Pascal"1.
Pitfalls
=in place of==. In C and C++,if (x = 0)assigns 0 tox, and the condition is always false. "Beginning programmers sometimes confuse assignment with the relational operator for equality, as "=" means equality in mathematics, and is used for assignment in many languages."1 GCC has the warning-Wparenthesesfor "an assignment in a context where a truth value is expected"7, and Python and Go reject the code. In JavaScript:
This code runs but gives a wrong answer on purpose.
let level = 3;
if (level = 0) {
console.log("zero");
} else {
console.log("not zero");
}
console.log(level);
not zero
0
The condition assigns 0, so the test is false, and level has lost its value.
- The order of a parallel assignment. Python and Go differ when a target uses a variable that the same statement changes:
This code runs but gives a wrong answer on purpose.
x = [0, 1]
i = 0
i, x[i] = 1, 2
print(x)
[0, 2]
Python assigns i = 1 first, and then x[i] is x[1]. The Python reference warns that such overlaps occur "left-to-right, sometimes resulting in confusion"2. Go computes the index before the assignments, so the same statement sets x[0]. Do not write such statements.
- Aliases. After
b = afor a list or an object,aandbrefer to one object. A change throughbshows througha. Copy the object when a separate value is needed. - A chain with a mutable value. In Python,
a = b = []makes one list with two names, not two lists.
Cost
An assignment of a simple value is one store to memory or a register, or nothing when the compiler keeps the value in a register. An assignment of a large struct in C, C++, Go or C# copies all its bytes. An assignment of a reference copies only the reference.
History
"The use of equals for assignment dates back to Heinz Rutishauser's language Superplan, designed from 1949 to 1951, and was particularly popularized by Fortran"1. Niklaus Wirth called it "A notorious example for a bad idea"1, because the sign = already meant a test for equality. ALGOL and Pascal used :=. "In C, the assignment operator is a single equals sign ("=") while the equality operator is a pair of equals signs ("==")."1
References
- Assignment (computer science), Wikipedia, Introduction; Semantics; Single assignment; Value of an assignment; Chained assignment; Parallel assignment; Assignment versus equality
- Simple statements, The Python Language Reference, 7.2 Assignment statements; 7.2.1 Augmented assignment statements
- Chapter 15, Expressions, The Java Language Specification, Java SE 25, 15.26 Assignment Operators
- Expressions, The Python Language Reference, 6.12 Assignment expressions
- The Go Programming Language Specification, Assignment statements
- Structure and Interpretation of Computer Programs, 2nd edition, section 3.1, Assignment and Local State, 3.1.1; 3.1.3
- Options to Request or Suppress Warnings, GCC manual, -Wparentheses
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 BCKNT2 Edit this page History Report an error Markdown