Scope and lifetime
Scope defines where variables are accessible in code, while lifetime defines how long variables persist in memory. Local variables have function scope and lifetimes tied to function execution. Global variables have program scope and persist throughout execution. Understanding scope prevents errors and resource leaks.
Real World
In Epic Games' Fortnite engine, a local variable tracking a bullet's position is created when the shot is fired and destroyed when it hits a surface, freeing memory — whereas the global player-count variable persists for the entire match.
Exam Focus
When asked why global variables are discouraged, cite unintended side effects and difficulty debugging in large programs.
How well did you know this?