Open In App

Variable Shadowing in C++

Variable shadowing is a common programming concept where a variable declared in some specific scope takes precedence over a variable with the same name declared in an outer scope. In C++, this can happen when you define a new variable within the function or block that has the same name as a variable declared in the outer scope.

Both global and local variables can be shadowed by the variables declared in the inner namespace. Let’s see each of them with examples and how we can avoid variable shadowing.



Local Variable Shadowing

This happens when there is a block inside a local scope and the variables with the same name are defined inside and outside of this block.

Example




// C++ Program to illustrate the local variable shoadowing
#include <iostream>
using namespace std;
  
int main()
{
    // Outer variable
    int x = 6;
    cout << "Outer x: " << x << endl;
    
    // Declare a new variable x within a function scope
    // shadowing the outer x
    if (true) {
        // Inner variable
        int x = 20;
        cout << "Inner x: " << x << endl;
    }
  
    // Access the outer x after the inner scope
    cout << "Outer x: " << x << endl;
    return 0;
}

Output

Outer x: 6
Inner x: 20
Outer x: 6

Explanation

In the above example in the main() function, the variable x = 6 is defined. Then in the if block, another variable with the same name x = 20 is defined inside the block. While printing the value of the variables outside and inside if block, we can see that the inner x shadowed the outer x, and the value 20 is printed.

Global Variable Shadowing

The global variables also get shadowed in the same way as the local variables but the difference is that they will always get shadowed in any local scope.

Example




// C++ program to demonstrate the global variable shadowing
#include <iostream>
using namespace std;
  
int x = 10;
  
int main()
{
    // local variable
    int x = 25;
  
    // printing x
    cout << x;
    
    return 0;
}

Output
25

How to Avoid Variable Shadowing?

The best way to avoid variable shadowing is to avoid using the same name for different variables. If you still want to declare the same name, you can use the namespace feature of C++. You can use some convention for naming local, global, instance, or static variables such that their names won’t be similar.

Related Articles:


Article Tags :