Scope and Lifetime
Scope determines where a variable can be used, while lifetime determines how long it exists during execution.
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.
globalScore is declared in global scope, so it is visible throughout the program and lives for the whole run.
Scope and lifetime answer different questions
| Aspect | Scope | Lifetime |
|---|---|---|
| Definition | Where a variable can be accessed. | How long a variable exists during execution. |
| Example | bonus is only visible inside the if block. | bonus exists only while that block is executing. |
| Question answered | Where can I use it? | When does it exist? |
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.