Author Topic: C++ - Difference between pass by value and pass by reference  (Read 1208 times)

kathir

  • Administrator
  • Sr. Member
  • *****
  • Posts: 283
C++ - Difference between pass by value and pass by reference
« on: December 12, 2011, 03:32:28 pm »
If you pass parameter by value, then a copy of the value is being passed. So if you change the value inside the function, it will not affect the caller. Pass by reference means if you change the value inside the function, then it would affect the caller. Refer to the following example with its output.

Code: (C++)
//Source Code Listing

#include <iostream.h>

void FnPassByRef(int &data)
{
   data = 200;
   std::cout << "Value Inside function Pass By Reference: " << data << "\n";
}

void FnPassByValue(int data)
{
   data = 300;
   std::cout << "Value Inside function Pass By Value: " << data << "\n";
}

int main()
{
   int data = 100;
   std::cout << "Initial Value: " << data  << "\n";
   FnPassByValue(data);
   std::cout << "Value After Calling function Pass By Value: " << data  << "\n";
   FnPassByRef(data);
   std::cout << "Value After Calling function Pass By Reference: " << data  << "\n";

   return 0;
}

/*** 
// Output
Inital Value: 100
Value Inside function Pass By Value: 300
Value After Calling function Pass By Value: 100
Value Inside function Pass By Reference: 200
Value After Calling function Pass By Reference: 200
Press any key to continue . . .
 
***/


 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1