Programming Search⌘K

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__)
Output
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 let variable 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 raises UnboundLocalError: "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

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript 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.
GoAbsent
RustNative
KotlinNativeThe 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.
SQLDoes not applyEach column of a row has a value or NULL, so a query cannot read a value that does not exist.
BashIdiomA 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.
PowerShellIdiomA 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.
HTMLDoes not applyHTML is markup, with no variables.
CSSDoes not applyEach property has an initial value, so no property is without a value.
Regular expressionsDoes not applyA 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
PythonGitHub
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)
Output
UnboundLocalError
11
  • Verdict: native. Python checks each read at run time. count += 1 binds count, so count is a local name in all of bump, and the read of the local name before it has a value raises UnboundLocalError, even though a global count exists. global count makes 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';
}
Output
9
-1
  • Verdict: native. As in C, int total; in a function has no known value. int total{}; gives 0. std::optional returns "no value" in the type, instead of an output variable that stays unset when the function fails, and value_or gives a value for that case.
JavaGitHub
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);
    }
}
Output
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 the default case, the compiler rejects the program, because label might not have a value. Array elements and fields have default values, such as null, 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;
}
Output
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: value starts at -1, so it has a known value when parse_digit fails 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);
Output
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 out parameter before it returns, so value has a value after the call, here 0 because the text is not a number. Both branches of the if assign label.
JavaScriptGitHub
function show() {
  return value;
}

try {
  show();
} catch (e) {
  console.log(e.name);
}
let value = 3;
console.log(show());

let later;
console.log(later === undefined);
Output
ReferenceError
3
true
  • Verdict: native. The rule is about time, not about the place in the text: show reads value, and the first call fails because the line let value = 3 has not run yet. After that line, the same call works. let later; has no initializer, so it holds undefined, 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)
	}()
}
Output
"" 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: p is nil, and the read of p.Name panics at run time. The deferred function recovers from the panic to show it.
RustGitHub
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}");
}
Output
one
7
  • Verdict: native. The compiler checks that each path assigns size before the read, and rejects the program if one arm of the match does not. The program name is the first argument, so n is 1. For memory that the program fills later, MaybeUninit holds a value that may not exist yet, and assume_init is unsafe: the programmer promises that the value is there.
  • 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 at undefined, and a comparison with undefined is always false, so the loop never sets max:

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);
Output
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

  1. Uninitialized variable, Wikipedia, Introduction; Example of the C language; Use in languages
  2. Chapter 16, Definite Assignment, The Java Language Specification, Java SE 25, Introduction
  3. Variables, C# language specification, 9.1 General
  4. Variables, The Rust Reference, variable.init
  5. let, MDN Web Docs, Temporal dead zone (TDZ)
  6. Execution model, The Python Language Reference, 4.2.2 Resolution of names
  7. Initialization, cppreference.com (C), Implicit initialization
  8. Default-initialization, cppreference.com (C++), Indeterminate and erroneous values
  9. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/MA9Q4F/text.yaml