Conceptcore
Uninitialized variables
Also called uninitialized variable, uninitialised variable, use before assignment, read before write, garbage value, indeterminate value, definite assignment, maybe-uninitialized, UnboundLocalError.
An uninitialized variable has no value that the program set before a read. In C and C++ the read gives an unpredictable value, and Java, C# and Rust reject the read at compile time.
- Applies to
- core-languages
Idea
"In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used."1 A loop that adds to a total needs a start value. Python reports the missing value when the read runs:
def total_price(prices):
for price in prices:
total = total + price
return total
try:
total_price([3, 4])
except UnboundLocalError as e:
print(type(e).__name__)
UnboundLocalError
The fix is one line: total = 0 before the loop. In C, the same mistake gives no error, and the result is a number that can change from run to run.
How it works
What the memory holds. A new variable gets a place in memory. In C, the place is on the stack, and the program does not clear it. "While the computer will set aside the appropriate amount of space for the stack frame, it usually does so simply by adjusting the value of the stack pointer, and does not set the memory itself to any new state (typically out of efficiency concerns)."1 So "whatever contents of that memory at the time will appear as initial values of the variables which occupy those addresses"1.
What the languages do. "Uninitialized variables are a particular problem in languages such as assembly language, C, and C++, which were designed for systems programming."1 Other languages close the gap in one of three ways:
- No read before a value, checked by the compiler. The compiler follows each path through the code and rejects a read on a path with no assignment. 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."2 C# has the same rule: "For an initially unassigned variable to be considered definitely assigned at a certain location, an assignment to the variable shall occur in every possible execution path leading to that location."3 In Rust, "Local variables can be used only after they have been initialized through all reachable control flow paths."4
- An error at run time. In JavaScript, a
letvariable read before its declaration line throws: "any attempt to access it will result in a ReferenceError"5. In Python, a local name without a value raisesUnboundLocalError: "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."6 - A default value. Go, and Java for fields, give each new variable a known value, see Default value. "Java does not have uninitialized variables."1
C and C++. In C, "objects with automatic storage duration are initialized to indeterminate values (which may be trap representations)"7. Wikipedia gives a loop that adds 1 to k ten times without a start value: "The final value of k is undefined."1 In C++, "If no initialization is performed for an object, that object retains an indeterminate value until that value is replaced."8 "Every other use of an indeterminate value is undefined behavior."8 See Undefined behavior. C++26 changes most of these values to erroneous values, "where each value is determined by the implementation independently of the state of the program"8, and "Every other use of an erroneous value is erroneous behavior: it may result in compile-time warning or error, run-time error, or an implementation-defined value."8
Compiler warnings. C and C++ compilers warn about some reads. GCC has -Wuninitialized, to "Warn if an object with automatic or allocated storage duration is used without having been initialized"9, and -Wmaybe-uninitialized for a path that may skip the assignment. The warnings are not complete: "These warnings are only possible in optimizing compilation, because otherwise GCC does not keep track of the state of variables."9 And GCC "is known not to warn in many situations (false negatives)"9.
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 the compiler reports a read of a let variable that is used before being assigned, when the type does not include undefined. No example file exists. |
| Go | Absent | |
| Rust | Native | |
| Kotlin | Native | The compiler rejects a read of a local variable before an assignment. A lateinit property has no value at first, and a read before an assignment throws an exception at run time. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | Each column of a row has a value or NULL, so a query cannot read a value that does not exist. |
| Bash | Idiom | A variable that was never set expands to the empty string with no error. The option set -u makes the expansion of an unset variable an error. No example file exists. |
| PowerShell | Idiom | A variable that was never assigned is $null with no error. Set-StrictMode -Version Latest makes the read an error. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup, with no variables. |
| CSS | Does not apply | Each property has an initial value, so no property is without a value. |
| Regular expressions | Does not apply | A pattern has no variables. |
| Language | Verdict | A read before a value |
|---|---|---|
| Python | native | UnboundLocalError for a local name, NameError for an unknown name |
| JavaScript | native | ReferenceError in the temporal dead zone of let and const; undefined after let x; |
| TypeScript | native | the rules of JavaScript; the compiler reports a read before an assignment |
| Java | native | a compile error for a local variable; fields have default values |
| Kotlin | native | a compile error for a local variable; lateinit throws at run time |
| C# | native | a compile error for a local variable; fields have default values |
| Go | absent | each variable has its zero value |
| Rust | native | a compile error; MaybeUninit in unsafe code |
| C | native | an indeterminate value, and undefined behavior |
| C++ | native | an indeterminate value; an erroneous value from C++26 |
| Bash | idiom | the empty string; set -u makes it an error |
| PowerShell | idiom | $null; strict mode makes it an error |
| SQL | n/a | each column of a row has a value or NULL |
| Regex | n/a | a pattern has no variables |
| HTML | n/a | HTML is markup, with no variables |
| CSS | n/a | each property has an initial value |
count = 10
def bump():
try:
count += 1
except UnboundLocalError as e:
print(type(e).__name__)
def bump_global():
global count
count += 1
bump()
bump_global()
print(count)
UnboundLocalError
11
- Verdict: native. Python checks each read at run time.
count += 1bindscount, socountis a local name in all ofbump, and the read of the local name before it has a value raisesUnboundLocalError, even though a globalcountexists.global countmakes the name refer to the global variable.
#include <iostream>
#include <optional>
#include <string>
std::optional<int> parse_digit(const std::string &s) {
if (s.empty() || s[0] < '0' || s[0] > '9') {
return std::nullopt;
}
return s[0] - '0';
}
int main() {
int total{};
for (const char *s : {"4", "x", "5"}) {
if (auto d = parse_digit(s)) {
total += *d;
}
}
std::cout << total << '\n';
std::cout << parse_digit("x").value_or(-1) << '\n';
}
9
-1
- Verdict: native. As in C,
int total;in a function has no known value.int total{};gives 0.std::optionalreturns "no value" in the type, instead of an output variable that stays unset when the function fails, andvalue_orgives a value for that case.
public class Main {
public static void main(String[] args) {
int code = args.length;
String label;
switch (code) {
case 0 -> label = "none";
case 1 -> label = "one";
default -> label = "many";
}
System.out.println(label);
String[] names = new String[1];
System.out.println(names[0] == null);
}
}
none
true
- Verdict: native. A local variable has no value until an assignment, and the compiler checks every path to a read. Each case of the switch assigns
label, so the read compiles. Without thedefaultcase, the compiler rejects the program, becauselabelmight not have a value. Array elements and fields have default values, such asnull, so the compiler does not check them.
#include <stdio.h>
#include <string.h>
static int parse_digit(const char *s, int *out) {
if (s[0] < '0' || s[0] > '9') {
return 0;
}
*out = s[0] - '0';
return 1;
}
int main(void) {
int value = -1;
if (!parse_digit("x", &value)) {
printf("no value: %d\n", value);
}
if (parse_digit("7", &value)) {
printf("value: %d\n", value);
}
char buf[8] = {0};
printf("%zu\n", strlen(buf));
return 0;
}
no value: -1
value: 7
0
- Verdict: native. C allows a variable with no value, and a read of it is undefined behavior, so a program that shows such a read has no fixed output. The safe habit is in this example:
valuestarts at -1, so it has a known value whenparse_digitfails and does not write it, and= {0}fills the whole buffer with zeros.
using System;
int value;
bool ok = int.TryParse("x", out value);
Console.WriteLine($"{ok} {value}");
string label;
if (DateTime.MinValue.Year == 1)
{
label = "first year";
}
else
{
label = "other";
}
Console.WriteLine(label);
False 0
first year
- Verdict: native. A local variable is initially unassigned, and the compiler rejects a read that some path reaches without an assignment. A method must assign each
outparameter before it returns, sovaluehas a value after the call, here 0 because the text is not a number. Both branches of theifassignlabel.
function show() {
return value;
}
try {
show();
} catch (e) {
console.log(e.name);
}
let value = 3;
console.log(show());
let later;
console.log(later === undefined);
ReferenceError
3
true
- Verdict: native. The rule is about time, not about the place in the text:
showreadsvalue, and the first call fails because the linelet value = 3has not run yet. After that line, the same call works.let later;has no initializer, so it holdsundefined, with no error.
package main
import "fmt"
type Config struct {
Name string
Retries int
}
func main() {
var c Config
fmt.Printf("%q %d\n", c.Name, c.Retries)
var p *Config
fmt.Println(p == nil)
func() {
defer func() {
fmt.Println("recovered:", recover() != nil)
}()
fmt.Println(p.Name)
}()
}
"" 0
true
recovered: true
- Verdict: absent. Go has no uninitialized variables: each variable starts at the zero value of its type. The risk moves to the nil pointer:
pis nil, and the read ofp.Namepanics at run time. The deferred function recovers from the panic to show it.
use std::mem::MaybeUninit;
fn main() {
let n = std::env::args().count();
let size: &str;
match n {
0 => size = "none",
1 => size = "one",
_ => size = "many",
}
println!("{size}");
let mut slot = MaybeUninit::<u32>::uninit();
slot.write(7);
let value = unsafe { slot.assume_init() };
println!("{value}");
}
one
7
- Verdict: native. The compiler checks that each path assigns
sizebefore the read, and rejects the program if one arm of thematchdoes not. The program name is the first argument, sonis 1. For memory that the program fills later,MaybeUninitholds a value that may not exist yet, andassume_initis unsafe: the programmer promises that the value is there.
Variations and related ideas
- Partial initialization. A struct or an array with some members set and others not. Wikipedia shows a C function that "leaks memory contents because it fails to fully initialize the members"1 of a struct before it copies the struct out.
- Out parameters. "C# has a special flavour of call-by-reference parameters to subroutines (specified as out instead of the usual ref), asserting that the variable is allowed to be uninitialized on entry but will be initialized afterwards."1
Pitfalls
- A wrong start value is as bad as none. In JavaScript,
let max;starts atundefined, and a comparison withundefinedis always false, so the loop never setsmax:
This code runs but gives a wrong answer on purpose.
let max;
for (const x of [-5, -2, -9]) {
if (x > max) {
max = x;
}
}
console.log(max);
undefined
Start with the first element, or with -Infinity.
- "It works on my machine." In C, an uninitialized variable can hold 0 by chance in a debug build and another value in an optimized build. A test that passes is no proof.
- Silence of the compiler. No warning does not mean no read. A read through a pointer, or in another function, is often not seen.
- A loop variable that keeps its old value. A variable declared outside a loop keeps the value of the last pass. Initialize it inside the loop when each pass needs a new start.
Cost
The check costs nothing when the program runs: the compiler does it. A run-time check, such as the temporal dead zone of JavaScript, costs a test on some reads. To initialize a variable costs one write. C and C++ save this write for each automatic variable, at the price of the bugs above.
History
Later languages reduced the problem: Java made definite assignment a compile-time rule and gave fields default values, and "many compilers will attempt to identify the use of uninitialized variables and report them as compile-time errors"1 even in languages that allow them.
References
- Uninitialized variable, Wikipedia, Introduction; Example of the C language; Use in languages
- 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), Implicit initialization
- Default-initialization, cppreference.com (C++), Indeterminate and erroneous values
- Options to Request or Suppress Warnings, GCC manual, -Wuninitialized; -Wmaybe-uninitialized
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 MA9Q4F Edit this page History Report an error Markdown