Course contentsShow
← C
Lesson 340 of 1,2195. FunctionsFree lesson

Shadowing variables in functions

Shadowing variables in functions

What you'll learn: How variables inside a function can "hide" variables with the same name from the outside world.

The "Local Hero" Rule

Imagine you are at a large wedding. There might be a guest named "Sam" sitting at a table in the corner. However, if your specific table also has a person named "Sam," and someone at your table shouts, "Hey Sam, pass the salt!", you automatically look at the Sam sitting right next to you. You "shadow" or ignore the other Sam across the room because the one in your immediate circle is more relevant.

In C, functions work the same way. When you define a parameter inside a function's parentheses, that name becomes a "local hero." Even if a variable with the exact same name exists outside the function (a global variable), the function will always prioritize its own version.

Seeing Shadowing in Action

When a local variable or parameter has the same name as a global variable, the global one is "shadowed." It still exists, but the function can't see it because the local name is standing directly in front of it.

#include <stdio.h>

// This is a global variable
int energy = 100;

void use_battery(int energy) {
    // The parameter 'energy' shadows the global 'energy'
    energy = energy - 10;
    printf("Inside function: %d\n", energy);
}

int main() {
    use_battery(50);
    printf("Outside function: %d\n", energy);
    return 0;
}

In this code, when use_battery(50) runs, the function creates its own local version of energy and sets it to 50. When it subtracts 10, it is only changing that local "copy." The global energy at the top of the file remains 100. The function is essentially wearing blinders; it only sees the energy passed into its parentheses.

Why does this matter?

Shadowing is a safety feature. It allows programmers to write functions without having to check every other line of code in the project to see if a variable name is already "taken." You can name your function parameters whatever makes the most sense for that specific task (like x, temp, or count) without worrying about accidentally breaking a variable with the same name located elsewhere in your program.

However, be careful: if you shadow a variable by accident, you might find yourself debugging a program where a value isn't changing when you expect it to. If you want to modify a global value, you must ensure the function doesn't have a local parameter blocking its view.

Key takeaway

A function always prioritizes its own local parameters and variables; if a name conflict exists, the local version "shadows" the outer version.