Shadowing a variable

What does shadowing a variable do?

For example, what is the difference between this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    #include <iostream>
using namespace std;
int main () {
int n;
cin>>n;
int counter = 0;
int x = 1;
do {
	int x = x*2;  
	counter ++;
}
while (counter<n);
cout<<x<<endl;
}

and this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  #include <iostream>
using namespace std;
int main () {
int n;
cin>>n;
int counter = 0;
int x = 1;
do {
	x = x*2;  
	counter ++;
}
while (counter<n);
cout<<x<<endl;
}
Have you tried running those two examples?
(It will help to put a cout<<"inside x="<<x<<"\n"; in between lines 10 and 11.)
it makes the code aggravating to read and debug.

Example 1 declares a SECOND, DISTINCT variable named x which is probably a bug. They exist at different scopes, so that is legal but unwise. It then loops to modify x #2 and then the scope falls away and the second x is destroyed along with all the work you just did. It then prints 1 because its the other x #1 that has never changed.


it is identical to this:
1
2
3
4
5
6
7
8
9
10
11
12
int main () {
int n;
cin>>n;
int counter = 0;
int x1 = 1;
do {
	int x2 = x2*2;  //double bug, x2 isn't initialized and its discarded. 
	counter ++;
}
while (counter<n);
cout<<x1<<endl;
}



example 2 had only 1 x and behaves as expected.


reusing variable names is usually bad. Its tolerated for standard loop variable names and in a few specific places, but be careful with it.

Last edited on
Topic archived. No new replies allowed.