Lesson 168 +10 XP

Variable Shadowing

Variable Shadowing

A name in an inner scope can reuse the name from an outer scope. The inner variable shadows (hides) the outer one.

What shadowing looks like

int value = 10;

int main() {
    int value = 20;       // shadows the outer value
    cout << value;        // prints 20
    return 0;
}

Inside main, the name value refers to the local variable. The outer value is hidden for the whole block.

Shadowing between blocks

It also happens between nested blocks:

int main() {
    int x = 5;
    {
        int x = 9;        // shadows the outer x
        cout << x;        // prints 9
    }
    cout << x;            // prints 5 again
    return 0;
}

As soon as the inner block ends, the outer x becomes visible again.

Why it's dangerous

The hidden variable still exists. You might think you're modifying the outer one while you're actually touching a copy that disappears at the block's end:

int main() {
    int score = 100;
    if (true) {
        int score = 0;    // oops, a new variable, not the original
        score = 50;       // the outer score is still 100!
    }
    cout << score;        // prints 100, not 50
    return 0;
}

How to avoid confusion

  • Don't reuse names across scopes. Give each variable a unique, descriptive name.
  • Enable compiler warnings about shadowing (-Wshadow in GCC/Clang) to catch it.
  • If you see a name redeclared, it's often a sign the code needs restructuring.

TL;DR

  • Shadowing: an inner variable hides an outer one with the same name.
  • Inside the inner block, the outer variable is unreachable by name.
  • Danger: you may edit the wrong variable and think the change stuck.
  • Fix: use unique names and turn on the -Wshadow warning.