Nov 27, 2014 at 4:48am UTC
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 Nov 27, 2014 at 4:49am UTC
Nov 27, 2014 at 4:53am UTC
Your test function takes a course by copy, rather than by reference, and the name of the parameter shadows the global object.
Nov 27, 2014 at 4:55am UTC
thanks, i got it the copy part
Last edited on Nov 27, 2014 at 5:06am UTC
Nov 27, 2014 at 5:05am UTC
but why u say it is shadowing? Isnt shadowing the same name occurring two or more times in different scopeS
Last edited on Nov 27, 2014 at 5:05am UTC
Nov 27, 2014 at 5:39am UTC
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.
Nov 27, 2014 at 6:12am UTC
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?
Nov 27, 2014 at 7:37am UTC
Do you understand what a copy is? If you change the copy, the original is not affected.
Last edited on Nov 27, 2014 at 7:37am UTC
Nov 27, 2014 at 8:29am UTC
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
Nov 27, 2014 at 8:37am UTC
When there is ambiguity, the closest enclosing scope is chosen. It's that simple.