Jul 7, 2012 at 6:10pm UTC
Hi all!
Could someone explain in detail to me what passing by reference actually is, and what the difference is between passing normal variables and passing them by reference? I think it's explained too abstract for me in the tutorial :)
Thanks in advance!
Jul 7, 2012 at 6:34pm UTC
Look at following example:
1 2 3 4 5 6 7 8 9 10
void foo(int value) {
value++; //same as value+=1 or value=value+1
}
int main() {
int myInt;
myInt=5;
foo(myInt);
cout << myInt;
}
this will out put 5, because when you call foo, you pass a copy of myInt, however:
1 2 3 4 5 6 7 8 9 10
void foo(int & value) {
value++; //same as value+=1 or value=value+1
}
int main() {
int myInt;
myInt=5;
foo(myInt);
cout << myInt;
}
will output 6, because you pass a reference to foo, allowing it to change myInt i.e. passing by reference.
Changed
Last edited on Jul 7, 2012 at 6:47pm UTC
Jul 7, 2012 at 6:45pm UTC
In Script Coder's second code line 1 should be void foo(int & value) {
Jul 7, 2012 at 6:46pm UTC
Oh sorry, I get confused sometimes, Thank You Peter.
Jul 7, 2012 at 7:22pm UTC
Thanks, Script Coder! I thought that passing by reference had something to do with variable adresses, but now I got it.
@Peter: I actually don't see any difference. What's different there?
Last edited on Jul 7, 2012 at 7:24pm UTC
Jul 7, 2012 at 7:37pm UTC
@Fransje: Sorry I changed it from a '*' to a '&'
Last edited on Jul 7, 2012 at 7:37pm UTC