functions pass by reference and pass by value

I dont understand why it is couting 1 6 3 and not 3 6 3. can someone please explain it? I cant seem to wrap this around my head.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  Given the following function definition

	void calc (int a, int& b)
{
   int c;

   c = a + 2;
   a = a * 3;
   b = c + a;
}

	What is the output of the following code fragment that invokes calc?  
	(All variables are of type int)
		
x = 1;
y = 2;
z = 3;
calc(x, y);
cout << x << "  " << y << "  "  << z << endl;
You pass x by value(i.e. a copy) so it doesn't change and keeps it's value 1.
y is passed by reference an it becomes 6.
z of course doesn't change it's value.
@thomas1965

thanks for the explanation. it makes a bit more sense now but here's another problem that I dont really get. i got 2 0 2 but the correct answer is actually 2 0 0.

#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;
}

Topic archived. No new replies allowed.