Scope rule

Why even thought add is global, when passed in function test it's value is not updated outside of function like test();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
struct course {
	
	float gStudents;
	char name[15];
	
	} add;

void test();
void test(course);		
int main(){
	
	test();
	cout<<"out func: "<<add.gStudents<<endl;
	test(add);
	cout<<"out func: "<<add.gStudents<<endl;//here it gives 5 
	return 0;
	}

void test(){
	add.gStudents=5;
	
	cout<<"In func: "<<add.gStudents<<endl;
	
	}
void test(course add){
	add.gStudents=6;
	
	cout<<"In func: "<<add.gStudents<<endl;
	
	



in func: 5
out func:5
in func: 6
out func:5 ///why not 6 as add is global
Last edited on
Your test function takes a course by copy, rather than by reference, and the name of the parameter shadows the global object.
thanks, i got it the copy part
Last edited on
but why u say it is shadowing? Isnt shadowing the same name occurring two or more times in different scopeS
Last edited on
Shadowing is when a variable has the same name as one in an outer enclosing scope. The global scope is an outer enclosing scope for everything, so any variable with the same name as something in the global scope will shadow it.
But i changed the param name to Add and still get the same output...Is it for add being passed as a copy to param Add?
Do you understand what a copy is? If you change the copy, the original is not affected.
Last edited on
Yes I do, What I meant was due to copy of the global the global var is not being changed....can you pls tell me hierarchy of shadow here:

There are five types of scopes in C++
Function
File
Block
Function Prototype //exception due to copy
Class
When there is ambiguity, the closest enclosing scope is chosen. It's that simple.
Topic archived. No new replies allowed.