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.
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.
Let's try to understand the concept of call by reference in C++ language by the example given below:
#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; }
void change(int& i) { i = 10; } int main() { int x = 0; // value type change(x); // reference is passed cout << x; // 10 }