Pass by reference (&) super confusing!

The correct answer is actually 2 0 0.
I understand why 2 is the answer but i dont understand the 0 0. Can someone please explain it? Im ready to pull my hair out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>
using namespace std;

void doSomething(int&);

int main()
{
int x = 2;

cout << x << endl;
doSomething(x);
cout << x << endl;
return 0;
}

void doSomething(int& num)
{
num = 0;
cout << num << endl;
}
Last edited on
Pass by reference ...
cout x, its 2, ok.
call dosomething. Num is now x. Its the same thing.
change num to 0. This changes x to 0, because num = x because num is a reference to x.
cout num, which is x, which is zero.
exit function.
cout x, which is 0, again.

can you explain what's the different between pass by reference and pass by value.
what's the different between pass by reference and pass by value.

"By reference" passes the actual variable itself. "By value"
passes a copy of the variable.

See the tutorial where it is covered in more detail:
http://www.cplusplus.com/doc/tutorial/functions/
Topic archived. No new replies allowed.