Passing by reference

Jan 15, 2012 at 5:54am
The following 2 programs seem to be paradoxical in the principal of "passing by reference"

PROGRAM 1
===============================================================================
#include <iostream>
using namespace std;

void figureMeOut(int& x, int y, int& z);

int main ()
{
int a,b,c;
a=10;
b=20;
c=30;
figureMeOut(a,b,c);
cout << a << " " << b << " "<< c << endl;
}

void figureMeOut(int& x, int y, int& z)
{
cout << x << " "<< y << " " << z << endl;
x=1;
y=2;
z=3;
cout << x << " "<< y << " " << z << endl;
}


OUTPUT
===============================================================================
10 20 30
1 2 3
1 20 3

Note: a,c change, but b does not =>those with the "&" change, those without do not. But this principle does not apply to the following program:



PROGRAM 2
===============================================================================
#include <iostream>
using namespace std;

void doStuff(int par1Value, int& par2Ref);

int main ()
{
int n1, n2;

n1=1;
n2=2;
doStuff(n1,n2);
cout << "n1 after function call = " << n1 << endl;
cout << "n2 after function call = " << n2 << endl;
}

void doStuff(int par1Value, int& par2Ref)
{
par1Value=111;
cout << "par1Value in function call = " << par1Value << endl;

par2Ref=222;
cout << "par2Ref in function call = " << par2Ref << endl;
}


OUTPUT
===============================================================================
par1Value in function call = 111
par2Ref in function call = 222
n1 after function call = 1
n2 after function call = 222


Jan 15, 2012 at 6:32am
That looks perfectly correct to me. In the second program n2 was changed from 2 to 222 by the function because it was passed by reference.
Topic archived. No new replies allowed.