Course contentsShow
← Computer Science
Lesson 212 of 2,8725. Functions and ModularityFree lesson

Variable Lifetime Basics

The duration a variable exists in memory from creation to destruction during program execution.

Variable Lifetime Basics

What you'll learn: You'll understand how long a variable actually exists in your program's memory, from the moment it's created until it disappears.

What Is Variable Lifetime?

Lifetime is the period during program execution when a variable occupies space in memory. It begins when the variable is created (usually at declaration) and ends when the variable is destroyed.

This is different from scope, which you just learned about. Scope tells you where you can see and use a variable's name. Lifetime tells you when the variable actually exists in memory.

An Everyday Analogy

Think of a temporary stage prop in a theater production. Its lifetime is from when the crew builds it before a scene until they tear it down after that scene ends. Its "scope" would be which parts of the stage it's visible from. The prop might exist backstage (alive but out of scope) or be destroyed entirely (end of lifetime).

Why Lifetime Matters

When a variable's lifetime ends, the memory it used is freed and can be reused. Trying to access a variable after its lifetime has ended leads to serious errors—you're reading memory that may now contain completely different data or nothing meaningful at all.

Variables typically have different lifetime rules:

  • Local variables come to life when their declaration is executed and die when their block/function exits
  • Global variables live for the entire program execution
  • Parameters exist only during the function call

Understanding lifetime helps you avoid bugs where you accidentally reference destroyed variables and helps you write memory-efficient programs.

Key Takeaway: A variable's lifetime is the duration it exists in memory during execution—know when your variables are born and die to write correct, efficient code.