A variable is declared with the same name as a variable in an outer scope, hiding the outer variable.
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;
}Use different names for variables in different scopes to avoid confusion.
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;
}