LearnForFree
C++ For Beginners
Lesson

Variable Scope & Lifetime

Scope defines the region of your code where a variable can be accessed, while lifetime defines how long that variable remains stored in your computer's RAM before being destroyed. 1. Local Scope (Block Scope) • Any variable declared inside a function or a pair of curly braces {} (such as inside an if block or for loop) is a local variable. • Scope: Accessible only from the line it is declared until the closing brace } of its block. • Lifetime: Created when execution enters the block and automatically destroyed (freed from memory) when execution exits the block. • Function parameters are also local variables to that function. 2. Global Scope • Variables declared outside of all functions (usually near the top of the file) are global variables. • Scope: Accessible from anywhere in the file below their declaration. • Lifetime: Created when the program starts and destroyed only when the program finishes running. • Best Practice: Avoid overusing mutable global variables, as any function can modify them unexpectedly, making bugs hard to track down. Global const values (like const double GRAVITY = 9.81;) are safe and common. 3. Variable Shadowing If a local variable has the exact same name as a global variable, the local variable temporarily hides ("shadows") the global variable inside that block. You can still access the global one using the scope resolution operator :: (e.g., ::count).
#include <iostream> int globalScore = 100; // Global variable void showScope() { int localBonus = 25; // Local to showScope() std::cout << "Inside showScope - Global: " << globalScore << "\n"; std::cout << "Inside showScope - Local: " << localBonus << "\n"; } int main() { int globalScore = 50; // Shadows the global variable inside main() std::cout << "Local shadowed score: " << globalScore << "\n"; // Prints 50 std::cout << "Actual global score: " << ::globalScore << "\n"; // Prints 100 showScope(); // std::cout << localBonus; // COMPILER ERROR! localBonus is out of scope here return 0; }

Watch companion video on YouTube

Sign in to save your progress