Pass by Reference vs Pass Value in C++ functions
By: Grant Braught
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;
}
Archived Comments
1. Thank you so much
View Tutorial By: Daniel at 2011-02-14 22:47:05
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Calculating total based on the given quantity and price in C++
Sorting an array of Strings in C++
Matrix using nested for loops in C++
Compute the square root of the sum of the squares of an array in C++
Calculate average using Two-Dimensional Array in C++
Two-Dimensional Array Manipulation in C++
Compiling and Linking Multiple Source Files in C++
Escape Sequences for Nonprintable Characters in C++
Using the Built-in Arithmetic Types in C++