Conceptintro
Variable
Also called variable, variables, program variable, local variable, global variable, mutable variable, storage location, named storage, var, let.
A variable is a name for a value that can change while the program runs. In some languages the name stands for a storage place that holds the value, and in others it refers to an object.
- Applies to
- core-languages
Idea
A program keeps its inputs, its counters and its partial results under names, so that a later step can use them. Such a name is a variable. In the classic description, "a variable is a named container for a particular set of bits or type of data"1. The program reads the variable to get the value, and it assigns to the variable to put a new value in it.
In Python, = gives a name a value, and a later = gives the same name a new value:
count = 0
for word in ["tea", "milk", "tea"]:
if word == "tea":
count = count + 1
print(count)
count = "done"
print(count)
2
done
The name count holds 0, then 1, then 2, and at the end the text done. "While a variable's name, type, and location often remain fixed, the data stored in the location may be changed during program execution"1.
How it works
A variable has a name, a place, a value and often a type. The name is in the source code. The place is memory that the compiler or the run time gives to the variable. The value is what the place holds now. "Compilers have to replace variables' symbolic names with the actual locations of the data"1.
The box model. In C, C++, Go, Java and C#, a variable is a box of a fixed type. The Go specification says: "A variable is a storage location for holding a value. The set of permissible values is determined by the variable's type."2 Java says the same: "A variable is a storage location and has an associated type"3, and C# says that "Variables represent storage locations"4. An assignment copies a value into the box. Two variables are two boxes, so a change to one does not change the other.
The label model. In Python, a variable is a name that refers to an object: "Names refer to objects. Names are introduced by name binding operations."5 An assignment does not copy the object. It makes the name refer to an object, so two names can refer to the same object. In such languages, "a variable is more accurately described as a name associated with a value, with memory allocation handled transparently by the interpreter or runtime"1.
References in a box. The two models meet in the box languages too. In Java, "A variable of a primitive type always holds a primitive value of that exact primitive type"3, but a variable of a class type holds a reference: "The reference values (often just references) are pointers to these objects"3. So int b = a copies a number, and int[] ys = xs copies a reference, and xs and ys then show the same array. The page Pointers and references has the details.
Change makes a variable a place. A variable that never changes is only a name for a value, as in mathematics. Assignment changes this. In the words of SICP, once the value of a variable can change, "a variable can no longer be simply a name. Now a variable somehow refers to a place where a value can be stored, and the value stored at this place can change."6 The order of the steps of the program then matters, because the same name gives different values at different times.
Imperative and functional languages. "In imperative programming languages, values can generally be accessed or changed at any time. In pure functional and logic languages, variables are bound to expressions and keep a single value during their entire lifetime due to the requirements of referential transparency."1 Rust takes a middle way: "by default, variables are immutable"7, and the keyword mut allows changes.
Static and dynamic types. "In statically typed languages such as C, C++, Java or C#, a variable also has a type, meaning that only certain kinds of values can be stored in it"1. "In dynamically typed languages such as Python, a variable's type is inferred by its value, and can change according to its value"1. The idea example shows this: count holds an integer and then a string.
Scope and lifetime. "The scope of a variable describes where in a program's text the variable may be used, while the extent (also called lifetime) of a variable describes when in a program's execution the variable has a (meaningful) value"1. The page Lexical scope describes scope.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the let, const and var of JavaScript, and adds a type annotation such as let n: number = 0, or a type that the compiler infers from the initializer. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin declares a variable with var and a name that is not reassigned with val, with a type annotation or an inferred type. No example file exists because kotlinc is not installed. |
| SQL | Idiom | A SQL query has no variables. It uses columns, parameters and the results of subqueries. The procedural extensions of database systems declare local variables with DECLARE. No example file exists. |
| Bash | Native | A Bash variable is a parameter with a name, set with n=0 and read with $n. The value is a string, and declare gives attributes such as -i for an integer and -r for read only. No example file exists. |
| PowerShell | Native | A PowerShell variable has a name that starts with $, such as $n = 0. It holds any object, and a type constraint such as [int]$n converts each new value. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup and has no variables. Scripts and template engines add them. |
| CSS | Idiom | CSS has custom properties, such as --gap set to 8px and read with var(--gap). They act as named values, but the cascade, not a program step, gives each element its value. No example file exists. |
| Regular expressions | Does not apply | A pattern has no variables. A capture group keeps the text that it matched, and a backreference such as \1 reads it, which is a related but different idea. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | a name bound to an object by =; no declaration; any type |
| JavaScript | native | let and var declare a variable, const a name that is not reassigned; any type |
| TypeScript | native | let and const, as in JavaScript, with a type annotation or an inferred type |
| Java | native | a typed storage location: int n = 0;, or var n = 0; with an inferred type |
| Kotlin | native | var for a variable and val for a name that is not reassigned |
| C# | native | a typed storage location: int n = 0;, or var n = 0; |
| Go | native | var n int or n := 0; a typed storage location |
| Rust | native | let x = 5; is immutable, let mut x = 5; can change |
| C | native | an object with storage: int n = 0;; &n gives its address |
| C++ | native | as in C, and auto n = 0; and references such as int& r = n; |
| Bash | native | a named shell parameter, n=0, read as $n; values are strings |
| PowerShell | native | $n = 0; any type, or a type constraint such as [int]$n |
| SQL | idiom | a query has no variables; procedural extensions declare local variables with DECLARE |
| Regex | n/a | a pattern has no variables; a group captures text, and a backreference such as \1 reads it |
| HTML | n/a | HTML is markup, with no variables |
| CSS | idiom | a custom property such as --gap: 8px, read with var(--gap); the cascade sets its value |
Bash. "A variable is a parameter denoted by a name. A variable has a value and zero or more attributes."8 The value is a string, and the attribute -i of declare makes the shell treat the value as an integer.
Go. A short variable declaration "is shorthand for a regular variable declaration with initializer expressions but no types"2: i, j := 0, 10 declares two variables of type int.
a = [1, 2]
b = a
b.append(3)
print(a, b, a is b)
b = [9]
print(a, b, a is b)
n = 1
n = "one"
print(n, type(n).__name__)
[1, 2, 3] [1, 2, 3] True
[1, 2, 3] [9] False
one str
- Verdict: native. A Python variable is a name that refers to an object, and
=binds the name.b = amakesbrefer to the same list, sob.append(3)changes the list thatashows too.b = [9]bindsbto a new list, andadoes not change. A name can refer to an object of any type.
#include <iostream>
int main() {
int n = 1;
int& alias = n;
alias = 2;
auto m = n;
m = 3;
std::cout << n << ' ' << alias << ' ' << m << '\n';
}
2 2 3
- Verdict: native. A C++ variable is an object with a type, as in C. A reference such as
int& alias = nis a second name for the same object, soalias = 2changesn.auto m = ndeclares a new object with a copy of the value.
public class Main {
public static void main(String[] args) {
int a = 1;
int b = a;
b = b + 1;
System.out.println(a + " " + b);
int[] xs = {1, 2};
int[] ys = xs;
ys[0] = 9;
System.out.println(xs[0] + " " + ys[0]);
var name = "Ada";
System.out.println(name.length());
}
}
1 2
9 9
3
- Verdict: native. A Java variable is a storage location with a type.
int b = acopies the number, so a change tobdoes not changea. An array variable holds a reference, soys = xscopies the reference, and both names show the same array.vartakes the type from the initializer:namehas the typeString, andname = 3does not compile.
#include <stdio.h>
int main(void) {
int n = 41;
int *p = &n;
*p = *p + 1;
printf("%d %zu\n", n, sizeof n);
return 0;
}
42 4
- Verdict: native. A C variable is an object: a region of storage with a type.
&ngives the address of the storage, and a write through the pointer changesn.sizeof ngives the size of the storage in bytes: 4 for aninton the machine that ran this example.
using System;
var p = new Point { X = 1 };
var q = p;
q.X = 2;
Console.WriteLine($"{p.X} {q.X}");
var r = new Box { X = 1 };
var s = r;
s.X = 2;
Console.WriteLine($"{r.X} {s.X}");
struct Point { public int X; }
class Box { public int X; }
1 2
2 2
- Verdict: native. A C# variable is a storage location with a type. A variable of a struct type holds the value, so
q = pcopies the struct, and a change toqdoes not changep. A variable of a class type holds a reference, sos = rmakes two names for one object.
let count = 1;
count += 1;
let value = 5;
value = "five";
console.log(count, typeof value, value);
const items = [1, 2];
items.push(3);
console.log(items);
try {
items = [];
} catch (e) {
console.log(e.name);
}
2 string five
[ 1, 2, 3 ]
TypeError
- Verdict: native.
letdeclares a variable in a block, and the variable can hold a value of any type.constdeclares a name that cannot get a new value, but the array that it refers to can still change. The assignmentitems = []throws aTypeErrorwhen it runs.
package main
import "fmt"
func main() {
var count int
fmt.Println(count)
count = 3
name := "Ada"
p := &count
*p = *p + 1
fmt.Println(count, name)
}
0
4 Ada
- Verdict: native.
var count intdeclares a variable with the zero value of its type, andname := "Ada"declares a variable and takes its type from the value. A Go variable is a storage location, so&countgives its address, and a write through the pointerpchangescount.
fn main() {
let x = 5;
let mut y = x;
y += 1;
let x = "five";
println!("{x} {y}");
}
five 6
- Verdict: native.
letdeclares a variable that cannot change, sox = 6afterlet x = 5does not compile.let mutallows changes. A secondlet xdeclares a new variable with the same name, which shadows the first one, and it can have another type.
Variations and related ideas
- Local and global variables. In Python, "If a name is bound in a block, it is a local variable of that block, unless declared as nonlocal or global. If a name is bound at the module level, it is a global variable."5 The other languages have the same split, with different rules.
- Constants. A name whose value does not change is a Constant. Many languages use the same syntax with another keyword:
constin JavaScript,finalin Java andvalin Kotlin. - Assignment and initialization. The first value of a variable is its initialization, and each later change is an assignment. See Initialization and Assignment.
- Binding. The link between the name and the place or the object is a Binding. Rebinding a name is a different thing from a change to the object that the name refers to.
- Aliasing. "A variable's storage location may be referenced by several different identifiers, a situation known as aliasing"1. A pointer in C, a reference in C++, and two names for one object in Python are aliases.
Pitfalls
- Two names for one object. In the label model, and for references in the box model, a change through one name shows through the other. A program that wants a separate value must copy it. In JavaScript:
This code runs but gives a wrong answer on purpose.
const scores = [10, 20];
const backup = scores;
scores.push(30);
console.log(backup);
const copy = [...scores];
scores.push(40);
console.log(copy);
[ 10, 20, 30 ]
[ 10, 20, 30 ]
backup is not a backup: it is the same array. The spread syntax [...scores] makes a new array.
- A typo makes a new variable. In Python, an assignment to a misspelled name makes a new variable, with no error. JavaScript outside strict mode has the same trap: an assignment to a name with no declaration "is an unqualified identifier assignment, which creates a global variable in non-strict mode"9.
- A read before the first write. A variable that has no value yet can give garbage, an error or a special value, by language. See Initialization.
- Long lived variables. A global variable can change anywhere in the program, so a reader cannot see all the places that change it. Keep variables in the smallest scope that works.
Cost
A local variable of a simple type costs a few bytes of stack memory or a register, and the compiler often removes it. A read or a write is one memory access or none. In the label model, each name is a reference, and the object lives on the heap, so a variable costs the reference and the object.
History
Variables came from mathematics, but "Variables in programming may not directly correspond to the concept of variables in mathematics. The latter is abstract, having no reference to a physical object such as storage location."1 Assignment-based programming with variables as places is the base of the imperative languages. SICP shows the cost of the idea. With assignment, "Our programming language can no longer be interpreted in terms of the substitution model of procedure application"6, the model that explains a function call as the replacement of each parameter by its value.
References
- Variable (high-level programming language), Wikipedia, Introduction; Actions on a variable; Scope and extent; Typing
- The Go Programming Language Specification, Variables; Short variable declarations
- Chapter 4, Types, Values, and Variables, The Java Language Specification, Java SE 25, 4.3.1; 4.12; 4.12.1
- Variables, C# language specification, 9.1 General
- Execution model, The Python Language Reference, 4.2.1 Binding of names
- Structure and Interpretation of Computer Programs, 2nd edition, section 3.1, Assignment and Local State, 3.1.1; 3.1.3
- Variables and Mutability, The Rust Programming Language, Introduction; Shadowing
- Shell Parameters, Bash Reference Manual, 3.4
- var, MDN Web Docs, Initialization of several variables
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 XYTFHJ Edit this page History Report an error Markdown