Pass by Reference and Value

I do not fully understand why the output of this code is what it is. WHat changes once "foo" is implemented?

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
26
27
28
29
30
31
32
33
34
35
int foo(int i, int & j)
{
	int result;
	i = 2 * j;
	j = i - 1;
	i = 12 + j / 2;
	if (j % 2 == 0)
	{
		i = 13 + i;
	}
	if (i % 3 == 1)
	{
		j = i - 1;
	}
	if (i > j)
	{
		result = i;
	}
	else
	{
		result = j;
	}
	return(result);
}

int main()
{
	int a = 1, b = 2, c = 3, d = 4, e = 5, f = 6;
	cout << foo(a, b);
	cout << foo(c, d);
	cout << foo(e, f);
	cout << "a = " << a << " b = " << b << " c = " << c
		<< " d = " << d << " e = " << e << " f = " << f << endl;
	return(0);
}
Your foo() starts:
1
2
3
4
5
int foo(int i, int & j)
{
  int result;
  i = 2 * j;
  j = i - 1;

Lets make a simpler example:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

void bar( int byvalue, int & byref ) {
  byvalue = 2 * byref;
  byref = byvalue - 1;
}

int main() {
  int x = 3, y = 7;
  bar( x, y );
  std::cout << "x=" << x << " y=" << y << '\n';
  return 0;
}

x=3 y=13

We call bar with x and y.
The value of x is copied to byvalue. Therefore, byvalue==3.
The byref is a reference to y. Therefore, byref==7.

New value is assigned to byvalue. Now byvalue==2*7==14

New value is assigned to byref. Now byref==14-1==13.
The byref is a reference to y and therefore y==13.


Edit:
Note that there is no reason to have the by value argument i on the function foo() because the first action of the function is to assign a new value to the i; the arguments value is never used. The i could/should be a local variable in foo().
Last edited on
Registered users can post here. Sign in or register to post.