C Compiler Logo

Shadowing Variable

Shadowing Variable

warning
warning: declaration shadows a variable in a wider scope

Description

A variable is declared with the same name as a variable in an outer scope, hiding the outer variable.

Common Causes

Example of Error

Error Code

int x = 10;  // Global x

int main() {
    printf("Global x: %d\n", x);
    
    {
        int x = 20;  // Local x shadows global x
        printf("Local x: %d\n", x);
    }
    
    return 0;
}

Solution

Use different names for variables in different scopes to avoid confusion.

Corrected Code

int global_x = 10;  // Clearly named global variable

int main() {
    printf("Global x: %d\n", global_x);
    
    {
        int local_x = 20;  // Clearly named local variable
        printf("Local x: %d\n", local_x);
    }
    
    return 0;
}

Additional Tips