Conceptintro
Initialization
Also called initialization, initialisation, initializer, initial value, initialize a variable, zero value, definite assignment, default initialization, temporal dead zone, initializer list.
Initialization gives a variable its first value. Some languages give a default value such as zero, others reject a read before it, and in C and C++ such a read can give a garbage value.
- Applies to
- core-languages
Idea
A Variable needs a value before the program can read it. "In computer programming, initialization or initialisation is the assignment of an initial value for a data object or variable."1 A sum starts at 0, a count starts at 0, and a flag starts at false:
total = 0
for price in [3, 4, 5]:
total = total + price
print(total)
12
The line total = 0 is the initialization. Without it, the first total + price has no value to add to.
How it works
Declaration and initialization. A Declaration makes a name known. Initialization gives the variable its first value. "Initialization is distinct from (and preceded by) declaration, although the two can sometimes be conflated in practice."1 In most languages, one line does both: int count = 0; declares count and initializes it. The part after = is the initializer. "Programming constructs which perform initialization are typically called initializers and initializer lists."1
Initialization is not assignment. An Assignment replaces the value of a variable that already has one. Initialization gives the first value. In most languages, the two look the same, but some rules apply only to one of them: a Constant accepts an initializer and rejects a later assignment, and a C++ object is made by a constructor at initialization, not by the assignment operator.
A variable without an initializer. Languages do one of four things:
- A default value. The language puts a known value into the variable. In Go, "If a list of expressions is given, the variables are initialized with the expressions following the rules for assignment statements. Otherwise, each variable is initialized to its zero value."2 Each element "is set to the zero value for its type: false for booleans, 0 for numeric types, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps"2. Java does the same for fields and array elements: "Each class variable, instance variable, or array component is initialized with a default value when it is created"3.
- A compile-time check. The compiler proves that each path to a read gives the variable a value first, and rejects the program if not. In Java, "For every access of a local variable declared by a statement x, or blank final field x, x must be definitely assigned before the access, or a compile-time error occurs."4 In C#, "A variable shall be definitely assigned (§9.4) before its value can be obtained."5 Rust has the same rule: "Local variables can be used only after they have been initialized through all reachable control flow paths."6
- An error at run time. In JavaScript, a
letvariable is in a "temporal dead zone" (TDZ) "from the start of the block until code execution reaches the place where the variable is declared and initialized"7. A read in this zone fails: "any attempt to access it will result in a ReferenceError"7. In Python, a name exists only after it is bound to a value, and a read before that raises an exception: "If the current scope is a function scope, and the name refers to a local variable that has not yet been bound to a value at the point where the name is used, an UnboundLocalError exception is raised."8 - No initialization. In C, "objects with automatic storage duration are initialized to indeterminate values (which may be trap representations)"9. The local variables of a function get whatever bits are in the memory. In C++, "If no initialization is performed for an object, that object retains an indeterminate value until that value is replaced."10 A read of such a value is Undefined behavior in C and in C++ before C++26.
Static variables in C and C++. C gives a zero value to the variables that live for the whole program. "objects with static and thread-local storage duration are empty-initialized"9: "pointers are initialized to null pointer values of their types", "objects of integral types are initialized to unsigned zero" and "objects of floating types are initialized to positive zero"9. So a global int count; is 0, but a local int count; is not.
Objects. In object-oriented languages, a constructor initializes a new object. "in object-oriented programming, initialization code may be part of a constructor (class method) or an initializer (instance method)."1 See Constructors and initialization.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the rules of JavaScript, and with strict checks the compiler reports a read of a let variable before an assignment, and a class property with no initializer. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | A local val or var must have a value before a read, which the compiler checks. A property needs an initializer, a value from the constructor, or the modifier lateinit. No example file exists because kotlinc is not installed. |
| SQL | Native | The DEFAULT clause of a column gives the value of a new row when the insert gives none. Without a default, the value is NULL. No example file exists. |
| Bash | Idiom | A variable that was never set expands to the empty string. The option set -u makes the expansion of an unset variable an error, and ${name:-default} gives a value for an unset variable. No example file exists. |
| PowerShell | Idiom | A variable that was never assigned is $null. Set-StrictMode -Version Latest makes a read of it an error. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup, with no variables. The value attribute gives a form control its first value. |
| CSS | Native | Each property has an initial value in its definition, and the keyword initial sets a property to it. No example file exists. |
| Regular expressions | Does not apply | A pattern has no variables to initialize. |
| Language | Verdict | Without an initializer |
|---|---|---|
| Python | native | no declaration; a name exists after its first binding, and a read before raises NameError or UnboundLocalError |
| JavaScript | native | let and const are in the temporal dead zone until their line; let x; and var give undefined |
| TypeScript | native | the rules of JavaScript, and the compiler reports a read of a let before an assignment |
| Java | native | fields and array elements get a default value; a local variable must be definitely assigned before a read |
| Kotlin | native | a local val or var must have a value before a read; a property needs an initializer or lateinit |
| C# | native | fields and array elements are initially assigned with the default value; a local variable must be definitely assigned |
| Go | native | each variable gets the zero value of its type |
| Rust | native | a let without a value must get one on all paths before a read; no default value |
| C | native | static variables are zero; automatic variables are indeterminate |
| C++ | native | as C for built-in types; a class type runs its default constructor |
| Bash | idiom | an unset variable expands to the empty string; set -u makes the expansion an error |
| PowerShell | idiom | an unassigned variable is $null; strict mode makes the read an error |
| SQL | native | a column default gives the value of a new row; without one, the value is NULL |
| Regex | n/a | a pattern has no variables |
| HTML | n/a | HTML is markup, with no variables |
| CSS | native | each property has an initial value, and the keyword initial sets it |
C++. C++ has many forms of initialization: int a = 1;, int a(1); and int a{1};. "Default-initialization is performed in three situations"10, the first "when a variable with automatic, static, or thread-local storage duration is declared with no initializer"10. For an int, default initialization does nothing, but int a{}; gives 0.
def count_words(words):
try:
print(count)
except UnboundLocalError as e:
print(type(e).__name__)
count = 0
for _ in words:
count += 1
return count
print(count_words(["a", "b", "c"]))
try:
print(missing)
except NameError as e:
print(type(e).__name__)
UnboundLocalError
3
NameError
- Verdict: native. Python has no declarations: the first binding of a name, such as
count = 0, is the initialization. A function that bindscountanywhere treatscountas a local name in the whole function, so a read before the binding raisesUnboundLocalError. A name with no binding at all raisesNameError.
#include <iostream>
#include <string>
#include <vector>
int main() {
int a{};
int b = 7;
std::string s;
std::vector<int> v1(3);
std::vector<int> v2{3};
std::cout << a << ' ' << b << " [" << s << "] " << s.size() << '\n';
std::cout << v1.size() << ' ' << v2.size() << ' ' << v2[0] << '\n';
}
0 7 [] 0
3 1 3
- Verdict: native.
int a{};gives 0, butint a;in a function leaves the value indeterminate. A class type such asstd::stringruns its default constructor, which makes an empty string. The two forms for a vector differ:v1(3)makes 3 elements of value 0, andv2{3}makes 1 element of value 3.
public class Main {
static int count;
static String name;
public static void main(String[] args) {
int[] scores = new int[3];
System.out.println(count + " " + name + " " + scores[1]);
int limit;
if (args.length > 0) {
limit = args.length;
} else {
limit = 10;
}
System.out.println(limit);
final int size;
size = 4;
System.out.println(size);
}
}
0 null 0
10
4
- Verdict: native. Fields and array elements get a default value: 0 for numbers and
nullfor references. A local variable has no default value. The compiler checks that each path giveslimita value before the read, and rejects the program if one path does not. Afinallocal variable can get its one value after the declaration.
#include <stdio.h>
static int counter;
struct point {
int x, y, z;
};
int main(void) {
static double total;
int local = 5;
int values[5] = {1, 2};
struct point p = {.y = 7};
printf("%d %.1f %d\n", counter, total, local);
printf("%d %d %d\n", values[1], values[2], values[4]);
printf("%d %d %d\n", p.x, p.y, p.z);
return 0;
}
0 0.0 5
2 0 0
0 7 0
- Verdict: native. Variables with static storage duration, such as
counterandtotal, are zero without an initializer. An automatic variable such aslocalneeds an initializer: without one, its value is indeterminate. An initializer for an array or a struct that gives some members sets the other members to zero.
using System;
int[] counts = new int[3];
string[] names = new string[2];
Console.WriteLine($"{counts[0]} {names[0] == null}");
Console.WriteLine($"{default(int)} {default(bool)} {default(double)}");
int number;
if (int.TryParse("42", out number))
{
Console.WriteLine(number);
}
0 True
0 False 0
42
- Verdict: native. Array elements and fields are initially assigned with the default value of their type, which
default(T)also gives. A local variable is initially unassigned, and the compiler rejects a read before an assignment on every path. Anoutargument counts as an assignment, sonumberhas a value after the call.
console.log(typeof early, early);
var early = 1;
try {
console.log(late);
} catch (e) {
console.log(e.name);
}
let late = 2;
let empty;
console.log(late, empty);
undefined undefined
ReferenceError
2 undefined
- Verdict: native. A
varvariable exists from the start of the function with the valueundefined, so the first line reads it with no error. Aletvariable is in the temporal dead zone until its line runs, and a read there throws aReferenceError.let empty;with no initializer givesundefined.
package main
import "fmt"
type Point struct {
X, Y int
}
func main() {
var i int
var s string
var p *int
var m map[string]int
var xs []int
fmt.Printf("%d %q %v %v %d\n", i, s, p == nil, m == nil, len(xs))
var pt Point
fmt.Println(pt, m["missing"])
n, name := 3, "Ada"
fmt.Println(n, name)
}
0 "" true true 0
{0 0} 0
3 Ada
- Verdict: native. Each variable without an initializer gets the zero value of its type, and a struct gets the zero value in each field. A nil map can be read, and a read of a missing key gives the zero value, but a write to a nil map panics.
:=declares and initializes in one step.
fn main() {
let limit: i32;
let big = std::env::args().count() > 5;
if big {
limit = 100;
} else {
limit = 10;
}
println!("{limit}");
let items: Vec<i32> = Vec::new();
let zero: i32 = Default::default();
println!("{} {}", items.len(), zero);
}
10
0 0
- Verdict: native. A
letwithout a value is allowed, and the compiler checks that each path gives the variable a value before the read. A read that some path does not cover is a compile error. Rust has no implicit default value:Default::default()gives one when the program asks for it.
Variations and related ideas
- Default values. A default value is the value that a variable gets when the program gives none, such as 0,
false,nullor the empty string. - Lazy initialization. The program computes the first value at the first read, for a value that is costly to make and may not be needed.
- Initialization order. In a class, the fields get their values in a fixed order, and a field that reads another field before it has its value can see a default value.
- Single assignment. In some languages, initialization is the only assignment: a name gets a value once and keeps it.
Pitfalls
- A sum without a start value. In JavaScript,
let total;givesundefined, andundefined + 3isNaN:
This code runs but gives a wrong answer on purpose.
let total;
for (const price of [3, 4, 5]) {
total += price;
}
console.log(total);
NaN
Write let total = 0;. In C, the same loop on an automatic variable without = 0 reads an indeterminate value, and the result can change from run to run.
- A default value hides a missing initialization. In Go and in Java fields, a variable that the program forgot to set is 0 or
null, with no error. The program goes on with a wrong value. - Reuse of the variable in a loop. A variable that collects values for each item must be initialized inside the loop, not once before it. Otherwise it keeps the values of the item before.
- A global zero is not a local zero. In C and C++,
int count;is 0 at file scope and indeterminate in a function.
Cost
Initialization to a default value costs a write of zeros, which is often free: C programs keep static data in a part of the program image that the system fills with zeros. "this form of initialization for statics is normally implemented by allocating them in the .bss section of the program image"9. For a large array, a language that zeroes each new array spends time on each element. C and C++ do not zero automatic variables, so a local variable without an initializer costs nothing. A compile-time check of definite assignment costs nothing when the program runs.
History
C leaves an automatic variable without an initializer indeterminate. Later languages added rules: Java gave default values to fields and made the compiler check that each local variable "must have a definitely assigned value when any access of its value occurs"4. Go made the zero value a rule for all variables, and C++26 changed the read of an uninitialized automatic variable from undefined behavior to an "erroneous value"10 that the implementation chooses.
References
- Initialization (computer programming), Wikipedia, Introduction
- The Go Programming Language Specification, Variable declarations; The zero value
- Chapter 4, Types, Values, and Variables, The Java Language Specification, Java SE 25, 4.12.5 Initial Values of Variables
- Chapter 16, Definite Assignment, The Java Language Specification, Java SE 25, Introduction
- Variables, C# language specification, 9.1 General
- Variables, The Rust Reference, variable.init
- let, MDN Web Docs, Temporal dead zone (TDZ)
- Execution model, The Python Language Reference, 4.2.2 Resolution of names
- Initialization, cppreference.com (C), Introduction; Implicit initialization; Empty initialization
- Default-initialization, cppreference.com (C++), Explanation; Indeterminate and erroneous values
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 MB0CJZ Edit this page History Report an error Markdown