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.
/*
* C++ Program to Illustrate Pass By Reference
*/
#include <iostream>
void passByReference(int& data)
{
std::cout << "Value of data in passByReference( ) is "
<< data << std::endl;
data = 20;
std::cout << "Value of data is changed now to "
<< data << std::endl;
return;
}
int main()
{
int data = 10;
std::cout << "Value of data is "
<< data << std::endl;
/* Variable data passed by reference */
passByReference(data);
/* Value of data is now 20 */
std::cout << "Value after calling passByReference( ) is "
<< data;
return 0;
}
$ 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.
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Practice Computer Science MCQs
- Practice Programming MCQs
- Check Computer Science Books
- Check Programming Books
- Apply for Computer Science Internship