value and reference parameters

Hi,
I am learning about value and reference parameters. There is an example in my book (see below) that I am having an issue understanding. the output for the question is:

**********
5, 10, 15
20, 10, 15
**********

How I think the output works is:

for the output after the function call for find(one, two, three):
because, int a, is a value parameter, it receives a copy of the variable, one, which is five. While the function executes, the variable one is manipulated, but as soon as the function exits, the variable returns to its original value of 5. Therefor the output is 5 because it is a value parameter.

Because, int& b, int& c, are reference parameters, they receive the corresponding address of the actual parameters, two and three, in the function call. Because they are reference parameters, whatever variable manipulation that occurs during the execution of the function remains after the function exits.( because both the formal and actual parameters share the same memory location).
The output of 10 and 15 therefor makes sense because int& b and int& c are reference parameters.

Now, the function call for find(two, one, three):
The output of 20, 10, 15: does not make as much sense to me. Specifically how did the function get 20 when two, the actual parameter for int a, is a value parameter. I don't understand why it is 20, and not 10, the actual value of the variable two.

Can someone maybe walk me through how the compiler might get these results.

Thanks,
DD

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
  #include <iostream>
using namespace std;

void find(int a, int& b, int& c,)
int main()
{
int one, two, three;
one = 5;
two = 10;
three = 15;
find(one, two, three);
cout << one << ", " << two << ", " << three << endl;
find(two, one, three);
cout << one << ", " << two << ", " << three << endl;

return 0;
}
void find(int a, int& b, int& c)
{
int temp;
c = a + b;
temp = a;
a = b;
b = 2 * temp;
}
You are passing one as second parameter in the second call which is a reference (referred by b inside the function) then b is getting 2 * temp. Temp here is same as two, having value of 10. 2 * 10 is 20 and since b is referring to one the value of b will be reflected in one

By the way the compiler is not getting these results, you logic is. Compiler job ended when it produced the object code for your source file.
Thanks codewalker,
That makes total sense.
Topic archived. No new replies allowed.