Variable Scope & Shadowing in C++
Understanding Scope and Variable Shadowing
In C++, variable scope defines the region of a program where a variable is accessible. When a local variable within a block shares the exact same name as an outer or global variable, variable shadowing occurs.
#### Key Rules:
1. Block Scope: Variables declared within braces { ... } exist only until the closing brace.
2. Inner Shadowing: The inner variable temporarily hides the outer variable with the same name.
3. Global Scope Operator `::`: You can explicitly access the global variable by prefixing the variable with the unary scope resolution operator ::.
#include <iostream>
int counter = 100; // Global
int main() {
int counter = 20; // Shadows global counter
{
int counter = 5; // Shadows main's counter
std::cout << ::counter << " " << counter << std::endl;
}
return 0;
}#### Mental Model Checklist:
::var to bypass all local shadowings and read global state directly.Practice & Output Prediction
Verify your understanding of this lesson. Answers are validated server-side.
What does the following C++ program print?
Note: Output verification is whitespace-tolerant.