Course contentsShow
← C
Lesson 138 of 1,2192. Variables and TypesFree lesson

Shadowing: Nested scope name clashes

Shadowing: Nested scope name clashes

What you'll learn: You will understand what happens when a new variable is declared inside a block using the same name as a variable in an outer block.

The "Sticky Note" Analogy

Imagine you are sitting at a desk with a sticky note that says price = 10. This note is stuck to the wall where you can always see it. Suddenly, you place a smaller box on your desk. Inside that box, you put a new sticky note that also says price = 5.

While your hands are inside that box, if you look for "price," you see the 5. The 10 on the wall hasn't disappeared—it’s just hidden, or "shadowed," by the note inside the box. Once you take your hands out of the box and look back at the wall, the 10 is still there, unchanged.

How Shadowing Works in C

In C, a variable's scope defines where that variable is visible. When you create a nested block (using curly braces { }), you create a new sub-scope. If you declare a variable inside that block with the exact same name as one in the outer scope, the inner variable "shadows" the outer one.

For the duration of that block, the program "forgets" the outer version exists. Any changes made to the inner variable do not affect the outer one.

#include <stdio.h>

int main() {
    int speed = 50; // The outer variable
    printf("Outer speed starts at: %d\n", speed);

    {
        // This is a new block. We "shadow" the outer speed.
        int speed = 100; 
        speed = speed + 20;
        printf("Inner speed (shadowing): %d\n", speed);
    } 

    // The inner 'speed' is now out of scope and destroyed.
    printf("Outer speed is still: %d\n", speed);

    return 0;
}

Why This Matters

Shadowing is a common source of bugs for beginners. You might think you are updating a global or outer variable, but because you accidentally typed a type name (like int) again inside a function or a loop, you’ve actually created a temporary "ghost" variable that vanishes as soon as the block ends.

To keep your code readable, it is generally best to give your variables unique names, even in different scopes, to avoid this confusion.

Key takeaway

Shadowing occurs when an inner scope declares a variable with the same name as an outer scope, temporarily hiding the outer variable without changing its value.