Pass by Value Program in C++

This C++ program illustrates how to pass a variable to a function by value. The value of the parameter can not be changed by using this method since we do not pass the variable’s address by either referencing operator (&) or using pointer.

Here is the source code of the C++ program illustrates how to pass a variable to a function by value. 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 Value
  3.  */
  4.  
  5. #include <iostream>
  6.  
  7. void passByValue(int data)
  8. {
  9.     std::cout << "Value of data in passByValue( ) 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 value */
  24.     passByValue(data);
  25.     /* Value of data is still 10 */
  26.     std::cout << "Value after calling passByValue() is "
  27.               << data;
  28.     return 0;
  29. }

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

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

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 & discussions at Telegram SanfoundryClasses.