Programming Search⌘K

Conceptcore

Variable lifetime

Also called variable lifetime, lifetime, extent, storage duration, automatic variable, static variable, static local variable, local lifetime, global lifetime, lifetime versus scope, out of scope.

The lifetime of a variable is the time that it exists while the program runs. A local variable lives for one call or block, a global one for the whole run, and a closure can make a local live longer.

Applies to
core-languages

Idea

A Variable does not exist for the whole run of a program. It comes into being, holds values, and then ends. "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

In Python, each call of a function makes new local variables, and a global variable lives for the whole run:

log = []


def visit(name):
    seen = []
    seen.append(name)
    log.append(name)
    return seen


print(visit("a"), visit("b"))
print(log)
Output
['a'] ['b']
['a', 'b']

seen is a new list on each call, so it holds one name. log lives from the start of the program to the end, so it keeps all the names.

How it works

Scope and lifetime. Scope is about text, and lifetime is about time. "The scope of a variable is actually a property of the name of the variable, and the extent is a property of the storage location of the variable."1 The two are often linked: "Entrance into that scope typically begins a variable's lifetime (as it comes into context) and exit from that scope typically ends its lifetime (as it goes out of context)."1 See Lexical scope.

The kinds of lifetime. C names them storage durations. "Every object has a property called storage duration, which limits the object lifetime."2

  • Automatic. "The storage is allocated when the block in which the object was declared is entered and deallocated when it is exited by any means (goto, return, reaching the end)."2 Local variables and parameters have this lifetime, on the stack. A recursive function gets new variables at each level.
  • Static. "The storage duration is the entire execution of the program, and the value stored in the object is initialized only once, prior to main function."2 Global variables have this lifetime, and so does a local variable marked static: its scope is the function, but it keeps its value from one call to the next.
  • Allocated, or dynamic. "The storage is allocated and deallocated on request, using dynamic memory allocation functions."2 The program calls malloc and free, or new and delete.
  • Thread. A thread-local variable lives as long as its thread.

Variables of objects. In Java, "A class variable is created when its class or interface is prepared (§12.3.2) and is initialized to a default value (§4.12.5)."3 A field of an object lives as long as the object: "The instance variable effectively ceases to exist when the object of which it is a field is no longer referenced, after any necessary finalization of the object (§12.6) has been completed."3

A lifetime longer than the scope. "it can be permissible for a variable binding to extend beyond its scope, as occurs in Lisp closures and C static local variables"1. A closure keeps the local variables that it uses alive after the function returns. Go moves a local variable to the heap when the program keeps its address: "unlike in C, it's perfectly OK to return the address of a local variable; the storage associated with the variable survives after the function returns."4

Variable lifetime and object lifetime. A variable that holds a reference is not the object. "In some programming contexts, object lifetime coincides with the lifetime of a variable that represents the object. In other contexts – where the object is accessed by reference – object lifetime is not determined by the lifetime of a variable."5 In Python and Java, the end of a variable ends only the reference, and a garbage collector frees the object later: "Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected."6 In C++ and Rust, the end of a variable ends the object that it holds. In Rust, "When a variable goes out of scope, Rust calls a special function for us. This function is called drop"7.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the lifetimes of JavaScript, with let and const for a block, var for a function, and closures that keep variables alive. No example file exists.
GoNative
RustNative
KotlinNativeKotlin has the lifetimes of the JVM. Local variables live for their block, properties live with their object, and the garbage collector frees objects. No example file exists because kotlinc is not installed.
SQLDoes not applyA query has no variables. A temporary table lives for a session or a transaction.
BashNativeA variable is global to the shell unless a function declares it with local, which makes it live for the call. No example file exists.
PowerShellNativeA variable lives in the scope where the program makes it, such as the global scope, a script or a function, and ends when that scope ends. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup, with no variables.
CSSDoes not applyA style sheet has no variables that start and end while a program runs.
Regular expressionsDoes not applyA pattern has no variables.
Language Verdict Lifetime of variables
Python native a local name lives for one call, to the end of the function, not the block; a closure keeps it alive
JavaScript native let and const live for a block, var for a function; closures keep them alive
TypeScript native the rules of JavaScript
Java native locals for a block, fields for their object, static fields while the class is loaded
Kotlin native the rules of the JVM: locals for a block, properties for their object
C# native locals for a block, fields for their object; using ends a resource at the end of the scope
Go native each variable lives while the program can reach it; the compiler puts it on the stack or the heap
Rust native a variable ends at the end of its scope, which runs drop; the borrow checker checks the lifetime of references
C native automatic, static, thread and allocated storage durations
C++ native the storage durations of C, and a destructor runs at the end of the lifetime of an object
Bash native variables are global unless local in a function, which lives for the call
PowerShell native a variable lives in its scope: the script, the function or the session
SQL n/a a query has no variables; a temporary table lives for a session or a transaction
Regex n/a a pattern has no variables
HTML n/a HTML is markup, with no variables
CSS n/a a style sheet has no variables that start and end in time
PythonGitHub
def make_counter():
    count = 0

    def step():
        nonlocal count
        count += 1
        return count

    return step


a = make_counter()
b = make_counter()
print(a(), a(), b())
Output
1 2 1
  • Verdict: native. A local variable normally ends when its call returns, but step uses count, so count lives as long as the function step. Each call of make_counter makes a new count, so a and b count apart. The objects themselves end when no name refers to them, at a time that the garbage collector chooses.
#include <iostream>
#include <string>
#include <utility>

struct Trace {
    std::string name;
    explicit Trace(std::string n) : name(std::move(n)) {
        std::cout << "make " << name << '\n';
    }
    ~Trace() {
        std::cout << "end " << name << '\n';
    }
};

int main() {
    Trace a("a");
    {
        Trace b("b");
    }
    Trace c("c");
}
Output
make a
make b
end b
make c
end c
end a
  • Verdict: native. An automatic object ends at the end of its block, and its destructor runs at that point. Objects in one block end in the reverse order of their construction, so c ends before a. This is the base of RAII: a destructor releases the resource that the object holds.
JavaGitHub
public class Main {
    static int created;
    int id;

    Main() {
        created++;
        id = created;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            Main m = new Main();
            System.out.println(m.id);
        }
        System.out.println(created);
    }
}
Output
1
2
3
3
  • Verdict: native. created is a class variable: it lives while the class is loaded and counts all the objects. id is an instance variable: each object has its own, which lives as long as the object. m and i are local variables of the loop, and each pass gets a new m.
#include <stdio.h>

static int next_id(void) {
    static int id = 0;
    id++;
    return id;
}

static int fresh_count(void) {
    int n = 0;
    n++;
    return n;
}

int main(void) {
    int first = next_id();
    int second = next_id();
    int third = next_id();
    printf("%d %d %d\n", first, second, third);
    int x = fresh_count();
    int y = fresh_count();
    printf("%d %d\n", x, y);
    return 0;
}
Output
1 2 3
1 1
  • Verdict: native. id has static storage duration: it is initialized once and keeps its value from call to call, though only next_id can see it. n has automatic storage duration: each call makes a new n that starts at 0 and ends when the call returns.
using System;

{
    using var r = new Resource("a");
    Console.WriteLine("in block");
}
Console.WriteLine("after block");

sealed class Resource : IDisposable
{
    private readonly string name;

    public Resource(string name)
    {
        this.name = name;
    }

    public void Dispose() => Console.WriteLine($"dispose {name}");
}
Output
in block
dispose a
after block
  • Verdict: native. A local variable lives for its block, and a field for its object, which the garbage collector frees later. For a resource, a using declaration calls Dispose when the variable goes out of scope, so the program knows when the file or the connection ends.
JavaScriptGitHub
function makeCounter() {
  let count = 0;
  return () => ++count;
}

const a = makeCounter();
const b = makeCounter();
console.log(a(), a(), b());

{
  let inner = "block";
  console.log(inner);
}
console.log(typeof inner);
Output
1 2 1
block
undefined
  • Verdict: native. A let variable lives for its block, and a var variable for its function. A closure keeps the variables that it uses alive, so each counter keeps its own count after makeCounter returns. Outside the block, the name inner does not exist, and typeof of an unknown name gives "undefined".
package main

import "fmt"

type Counter struct {
	n int
}

var total int

func newCounter() *Counter {
	c := Counter{}
	return &c
}

func main() {
	p := newCounter()
	p.n++
	p.n++
	total += p.n
	fmt.Println(p.n, total)
}
Output
2 2
  • Verdict: native. A variable lives as long as the program can reach it. c is a local variable of newCounter, but the function returns its address, so the compiler puts c on the heap and it lives on. total is a package variable, which lives for the whole run.
RustGitHub
struct Noisy(&'static str);

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("drop {}", self.0);
    }
}

fn main() {
    let _a = Noisy("a");
    {
        let _b = Noisy("b");
        println!("inner end");
    }
    let c = Noisy("c");
    drop(c);
    println!("main end");
}
Output
inner end
drop b
drop c
main end
drop a
  • Verdict: native. A value ends when the variable that owns it goes out of scope, and Rust runs drop at that point: _b at the end of the inner block, and _a at the end of main. drop(c) moves c into a function, which ends it early. The compiler also checks that no reference lives longer than its value.
  • Stack and heap. Automatic variables are on the stack, and the end of a call frees them at once. Values on the heap live until the program, a garbage collector or a destructor frees them.
  • RAII. In C++ and Rust, the end of a variable runs code that releases a resource such as a file or a lock. Other languages have with, using and try with resources for the same purpose.
  • Lifetimes in Rust types. Rust checks that a reference does not live longer than the value that it refers to.
  • Escape analysis. A compiler finds the local variables that outlive their call and puts only those on the heap.

Pitfalls

  • A variable that lives longer than expected. A Python variable lives to the end of the function, not the end of a loop, so code after the loop can read the loop variable. With an empty list, the loop never assigns it:

This code runs but gives a wrong answer on purpose.

def last_item(items):
    for item in items:
        pass
    return item


print(last_item([1, 2, 3]))
try:
    last_item([])
except UnboundLocalError as e:
    print(type(e).__name__)
Output
3
UnboundLocalError

Use items[-1] with a check for an empty list instead.

  • A pointer to a variable that ended. In C and C++, the address of a local variable is not valid after the function returns. "A variable whose extent ends before its scope may become a dangling pointer"1. A read through it is undefined behavior.
  • A static local variable is shared. All calls, and all threads, see the same variable.
  • A closure keeps memory. A closure that a program keeps also keeps all the variables that it uses, and the objects that they refer to.

Cost

An automatic variable costs almost nothing to make and to end: the call moves the stack pointer. A static variable costs nothing at run time. A variable on the heap costs an allocation, and later a free or work for the garbage collector. "For space efficiency, a memory space needed for a variable may be allocated only when the variable is first used and freed when it is no longer needed."1

History

The kinds of lifetime grew with the languages. C has automatic, static and allocated storage, and C11 added thread storage duration2. Languages with a garbage collector, such as Java and Python, end the life of an object some time after no variable refers to it. Rust checks the lifetimes of references in the compiler, with no garbage collector.

References

  1. Variable (high-level programming language), Wikipedia, Scope and extent
  2. Storage-class specifiers, cppreference.com (C), Storage duration
  3. Chapter 4, Types, Values, and Variables, The Java Language Specification, Java SE 25, 4.12.3 Kinds of Variables
  4. Effective Go, Composite literals
  5. Object lifetime, Wikipedia, Introduction; Determinism
  6. Data model, The Python Language Reference, 3.1 Objects, values and types
  7. What Is Ownership?, The Rust Programming Language, Memory and Allocation

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/FGQ4Y5/text.yaml