Scope and Lifetime

► Understanding Scope and Lifetime

Scope and lifetime are fundamental concepts that determine where and how long variables exist in your program. Scope defines where a variable can be accessed, while lifetime determines how long a variable stays in memory.

► Real-World Analogy

Think of scope and lifetime like access to different rooms in a house:
» Your bedroom is your private space (local scope) – only you can access items there
» The living room is shared space (global scope) – everyone in the house can access it
» A note you write exists only while you’re in that room (lifetime)
» Once you leave and close the door, temporary notes disappear (variable destroyed)

► Key Concepts

✓ Local scope: Variables created inside functions
✓ Global scope: Variables created outside all functions
✓ Lifetime: Duration a variable exists in memory
✓ LEGB rule: Local, Enclosing, Global, Built-in lookup order
✓ Variable shadowing: Local variables can hide global ones

■ Code Examples