C++ Call by Reference

There are two ways to pass value or data to function in C++ language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

In call by reference, original value is modified because we pass reference (address).

Hence, value changed inside the function, is reflected inside as well as outside the function.

Note
To understand the call by reference, you must have the basic knowledge of pointers.

We can pass a variable by reference by adding an ampersand before the parameter’s name in the function’s definition. Here, address of the value is passed in the function, so actual and formal arguments share the same address space. So when arguments are passed by reference, both primitive and object data types can be changed or replaced and the changes will affect the original.

Example #1

Let's try to understand the concept of call by reference in C++ language by the example given below:

snippet
#include<iostream>
using namespace std;  
void swap(int *x, int *y)
{
 int swap;
 swap=*x;
 *x=*y;
 *y=swap;
}
int main() 
{  
 int x=500, y=100;  
 swap(&x, &y);  // passing value to function
 cout<<"Value of x is: "<<x<<endl;
 cout<<"Value of y is: "<<y<<endl;
 return 0;
}
Output
Value of x is: 100 Value of y is: 500
Example #2
snippet
void change(int& i) { i = 10; }
int main()
{
int x = 0; // value type
change(x); // reference is passed
cout << x; // 10
}
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +