MASIGNASUKAv102
6510051498749449419

Call by value and call by reference - Learn With AVRK

Add Comments
Thursday, September 2, 2021

Call by value and call by reference in C++ Language

In C++ language, there are two methods to pass value or data to a function -
  • Call by value
  • Call by reference

In call by value method the original value does not changed whereas It changed in call by reference method.

Loading...
Let us understand call by value and call by reference one by one in detail -

Call by value in C++

In call by value, the original value is not changed. The value which is passed to any function is stored by the function parameter in the stack memory location. If you change the values of a function parameter, it is changed only for the current function. It never changes the value of  variable inside the caller method such as main() function.

Let's try to understand the concept of call by value with an example given below -
#include<iostream>
using namespace std;
void change(int data);
int main()
{
    int data = 5;
    change(data);
    cout << "Value of the data is: " << data<< endl;
    return 0;
}
void change(int data)
{
    data = 10;
}


Output -

Value of the data is : 3


Call by reference in C++

In call by reference, the original value is modified as we pass the reference (address).
Here, the address of values are passed to the function parameters, by which the actual and formal arguments share the same address space. Therefore, the value changed inside the function is reflected inside as well as outside.

Note : To understand call by reference, you need to have basic knowledge of pointers.

Let us look an example to understand the concept of call by reference -
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
    int swap;
    swap=*x;
    *x=*y;
    *y=swap;
}
int main()
{
    int x=100, y=200;
    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: 200
Value of y is: 100


Difference between call by value and call by reference

No. Call by value Call by reference
1 A copy of the value is passed to the function. An address of value is passed to the function.
2 Changes made inside the function is not reflected on other functions. Changes made inside the function is reflected outside the function also.
3 Actual and formal arguments are be created in different memory location. Actual and formal arguments are be created in same memory location.

Also check out this : C++ Functions - Learn With AVRK
Learn With AVRK

Learn With AVRK