Passing by Reference

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!
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
In Script Coder's second code line 1 should be void foo(int& value) {
Oh sorry, I get confused sometimes, Thank You Peter.
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
@Fransje: Sorry I changed it from a '*' to a '&'
Last edited on
Topic archived. No new replies allowed.