Pass by Reference vs Pass Value in C++ functions

By: Grant Braught Viewed: 153175 times    

This sample C++ program, demonstrates the difference of Pass by Reference and Pass by Value parameters in C++ functions.
#include 

// Function prototypes...
int Puzzle1(int A, int &B, int &C);
int Puzzle2(int A, int &B, int &C);

int main()
{
	int X = 3;
	int Y = 2;
	int Z = 7;
	
	cout << "Before Puzzles:" << endl;
	cout << "X = " << X << endl;
	cout << "Y = " << Y << endl;
	cout << "Z = " << Z << endl << endl;
	
	X = Puzzle1(X,Y,Z);

	cout << "After Puzzle1:" << endl;
	cout << "X = " << X << endl;
	cout << "Y = " << Y << endl;
	cout << "Z = " << Z << endl << endl;
	
	Z = Puzzle2(X,Y,Z);

	cout << "After Puzzle2:" << endl;
	cout << "X = " << X << endl;
	cout << "Y = " << Y << endl;
	cout << "Z = " << Z << endl;
	
	return 0;
}

int Puzzle1(int A, int &B, int &C)
{
	int D;
	
	C = A;
	D = B;
	B = A;
	A = D;
	
	return D;
}

int Puzzle2(int A, int &B, int &C)
{
	int i;
	
	for (i=1; i<=5; i++)
	{
		B = B + C;
		A = A - B;
		C++;
	}
	
	return C;
}

Most Viewed Articles (in C++ )

Latest Articles (in C++)

Comment on this tutorial