Call by Value and Call by Reference in C++ with Example
Call by Value:
It is a method of passing arguments that are used to a function and copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function do not affect the argument. By default, C++ uses call-by-value to pass arguments.
Example:
#include<iostream.h> #include<conio.h> void swap(int x, int y) { int temp; temp=x; x=y; y=temp; } void main() { int x=25, y=50; clrscr(); swap(x, y); // passing value to function cout<<"The Value of x: "<<x; cout<<"The Value of y: "<<y; getch(); }
Output:
The Value of x: 50
The Value of y: 25
Call by Reference:
In C++, it permits us to pass parameters to the function by reference. When we pass the arguments by reference, the formal arguments in the called function become aliases to the actual arguments in the calling function which means when the function is working with its arguments.
void swap(int *a, int *b) { int n; n=*a; // assign the value at the address a to n // *a=*b; *b=n; } swap(&x, &y); // call by passing //
Example:
#include<iostream.h> #include<conio.h> void swap(int *x, int *y) { int temp; temp=*x; *x=*y; *y=temp; } void main() { int x=25, y=50; clrscr(); swap(&a, &b); // passing value to function cout<<"The Value of x:"<<x; cout<<"The Value of y:"<<y; getch(); }
Output:
The Value of x: 50
The Value of y: 25
Actual Arguments:
The arguments listed in the function calling statement that is called Actual Arguments.
Formal Arguments:
The arguments used in the function declaration that is called Formal Arguments.
We can difference between Call by Value and Call by Reference is given below:
Call by Value vs Call by Reference:
1. It is a usual method to call a function in which only the value of the variable is passed as an argument. | 1. In this method, the address of the variable is passed as an argument. |
2. Memory location occupied by formal and actual arguments is different. | 2. Memory location occupied by formal and actual arguments is same. |
3. Any alteration in the value of the argument passed is local to the function and it's not accepted in the calling program. | 3. Any alteration in the value of the argument passed is local to the function and it is accepted in the calling program. |
4. This method is slow. | 4. This method is fast. |
5. There is no possibility of wrong data manipulation because the arguments are directly used in an expression. | 5. There is a possibility of wrong data manipulation because the addresses are directly used in an expression. |