Scope and Lifetime

Scope determines where a variable can be used, while lifetime determines how long it exists during execution.

Programming Languages

Scope controls visibility. Lifetime controls existence.

Scope and lifetime are two different attributes of a variable. Scope determines where in the program a variable can be accessed. Lifetime determines how long the variable exists during execution. A variable may be in scope only inside a block, while its lifetime depends on when that block begins and ends.

How to read the demo

The simulation shows the same variable from two angles: where it is visible and how long it stays alive.

  • Watch the highlighted line to see where execution currently is.
  • Use the scope view to see which block is active and which variables are visible there.
  • Use the lifetime panel to see variables appear, fade, and disappear as execution moves.

Step through one short program and watch variables become visible, go out of scope, and disappear when their lifetime ends.

Code snippet
1int globalScore = 10;
2
3void play() {
4 int level = 1;
5 if (level > 0) {
6 int bonus = 5;
7 }
8}
Scope view
Global scopeActive
globalScore
play() scopeExited
level not created
if blockExited
bonus not created
Variable lifetime panel
globalScoreIn scope
Type: int
Value: 10
Address: 0x100
Scope: Global scope
Lifetime: Whole program
levelDestroyed
Type: int
Value:
Address:
Scope: Inside play()
Lifetime: During play() only
bonusDestroyed
Type: int
Value:
Address:
Scope: Inside if block
Lifetime: During if block only

globalScore is declared in global scope, so it is visible throughout the program and lives for the whole run.

1 / 6
Comparison Summary

Scope and lifetime answer different questions

AspectScopeLifetime
DefinitionWhere a variable can be accessed.How long a variable exists during execution.
Examplebonus is only visible inside the if block.bonus exists only while that block is executing.
Question answeredWhere can I use it?When does it exist?
Key Takeaways

The short version

  • Scope is about visibility.
  • Lifetime is about existence.
  • Variables can appear and disappear as execution enters and leaves blocks.
  • Global, local, and block variables behave differently.