Pass by Reference in C++

«
»
This C++ program illustrates how to pass a variable to a function by reference. The value of the parameter can be changed by using this method. The referencing operator (&) is used in the function definition only and not when the function is called like in pointers where the address was passed whenever the function is called. Also no special dereferencing is required while using pass by reference.

Here is the source code of the C++ program illustrates how to pass a variable to a function by reference. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Illustrate Pass By Reference
  3.  */
  4.  
  5. #include <iostream>
  6.  
  7. void passByReference(int& data)
  8. {
  9.     std::cout << "Value of data in passByReference( ) is "
  10.               << data << std::endl;
  11.     data = 20;
  12.     std::cout << "Value of data is changed now to "
  13.               << data << std::endl;
  14.     return;
  15. }
  16.  
  17. int main()
  18. {
  19.     int data = 10;
  20.  
  21.     std::cout << "Value of data is "
  22. 	      << data << std::endl;
  23.     /* Variable data passed by reference */
  24.     passByReference(data);
  25.     /* Value of data is now 20 */
  26.     std::cout << "Value after calling passByReference( ) is "
  27.               << data;
  28.     return 0;
  29. }

$ a.out
Value of data is 10
Value of data in passByReference( ) is 10
Value of data is changed now to 20
Value after calling passByReference( ) is 20

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.