Learn/C++ Fundamentals & Execution Tracing/Variable Scope & Shadowing in C++
C++ 15 min 1 Questions

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 ::.

cpp
#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:

  • Identify every variable definition level (Global, Function, Inner Block).
  • When a name is evaluated, the compiler searches innermost to outermost.
  • Use ::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.

    Question 1 of 1 • 10 ptsoutput prediction

    What does the following C++ program print?

    Note: Output verification is whitespace-tolerant.

    Next Lesson