Home CPP Call by value and call by reference in C++

Call by value and call by reference in C++

There are two ways to pass arguments to a function in CPP: Call by Value or Call by Reference. The Call by Value is the most popular way of passing arguments to a function. The difference between the two is how the values are passed in them as arguments.

Call By Value

In call by value, the value passed to a function is locally stored by the function in a stack of memory allocated to the function, so the two types of parameters are stored in different memory locations. Hence any changes made to the value are local to the function and the changes will not be reflected in the actual values of the caller.

// CPP program to explain
// call by value

#include <bits/stdc++.h>
using namespace std;

// Swap functions that swaps
// two values
void swapx(int x, int y)
{
    int temp;

    temp = x;
    x = y;
    y = temp;

    cout<<"x="<<x<<" y="<<y<<endl;
}

// Main function
int main()
{
    int a = 10, b = 20;

    // Pass by Values
    swapx(a, b);

    cout<<"a="<<a<<" b="<<b<<endl;

    return 0;
}

Output
x=20 y=10
a=10 b=20

The actual values of a and b remain unchanged even after exchanging the values of x and y.

Call By Reference

In call by reference, the value passed to a function refers to the location where the actual variable is stored, because instead of the actual value the address of the value is passed in the function.

// CPP program to explain
// call by reference

#include <bits/stdc++.h>
using namespace std;

// Swap functions that swaps
// two values
void swapx(int *x, int *y)
{
    int temp;

    temp = *x;
    *x = *y;
    *y = temp;

    cout<<"x="<<*x<<" y="<<*y<<endl;
}

// Main function
int main()
{
    int a = 10, b = 20;

    // Pass by Reference
    swapx(&a, &b);

    cout<<"a="<<a<<" b="<<b<<endl;

    return 0;
}
Output
x=20 y=10 
a=20 b=10

The actual values of a and b are changed after exchanging the values of x and y.

In C and CPP we use pointers to achieve call by reference.

Further Reading

The parameters passed to the function are called actual parameters whereas the parameters received by the function are called formal parameters.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subscribe to our weekly newsletter

Join our community of 1000+ developers and stay updated with the fast moving world of computer science

We promsie, we won't spam
Even we hate spam as much as you hate them

Books recommendation for interview preparation