### 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?

 ``1234567891011121314151617181920212223242526272829303132333435`` ``````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); }``````
 ``12345`` ``````int foo(int i, int & j) { int result; i = 2 * j; j = i - 1;``````

Lets make a simpler example:
 ``12345678910111213`` ``````#include 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
Topic archived. No new replies allowed.