A variable with same in a function as that of the name of global variable

Please check the following code,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;
struct temp
{
	int a;

}s; 

void change(struct temp);
int main()
{
	s.a = 10;
	change(s); 
	cout << s.a << endl; 
	system("pause");
	return 0;

}
void change(struct temp s)
{
	s.a = 1; 
	cout << s.a << endl; 
}


Now, if you look at the result, it gives you
1
2
1 // From Function
10 // of Global variable 


Why does the compiler use the "s" of function (local variable) and not the global variable? And in fact, shouldn't it show an error here? since you are declaring a variable in a function with a name that is already used previously for a global variable?

Moreover, even there's reason behind because of which it is allowing this, then how can we use the Global variable in the function when another variable with same name is already declared? Please clear, thank you!
Why does the compiler use the "s" of function (local variable) and not the global variable?

Because that's how C++ works. It is known as "shadowing" and it is expected.

And in fact, shouldn't it show an error here? since you are declaring a variable in a function with a name that is already used previously for a global variable?

No. This is not an error. This is how C++ works. If you don't want this to happen, don't write code that does this.

Moreover, even there's reason behind because of which it is allowing this, then how can we use the Global variable in the function when another variable with same name is already declared?


1
2
3
4
5
6
void change(struct temp s)
{
	s.a = 1; 
	cout << s.a << endl; 
	::s.a=55;
}
Topic archived. No new replies allowed.