Programming Tutorials

Pass by Reference vs Pass Value in C++ functions

By: Grant Braught in C++ Tutorials on 2011-01-27  

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

// 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;
}





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)