C++ Call by Value & Call by Reference

Hi everyone, inside this article we will see about C++ Call by Value Vs Call by Reference.

In C++, there are two methods for passing arguments to functions: call by value and call by reference.

Call by Value in C++

This method involves passing a copy of the argument’s value to the function. Any changes made to the argument within the function are not reflected in the caller. This method is useful when you want to pass an argument to a function, but you don’t want the function to modify the original argument.

In call by value, original value is not modified.

Example

#include <iostream>
using namespace std;

void increment(int a)
{
    a++;
}

int main()
{
    int x = 5;
    increment(x);
    cout << x << endl; // Output: 5
    return 0;
}

Output

5

Call by Reference in C++

This method involves passing a reference to the argument to the function, instead of a copy of the argument’s value. Any changes made to the argument within the function are reflected in the caller. This method is useful when you want to pass an argument to a function, and you want the function to modify the original argument.

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

Example

#include <iostream>
using namespace std;

void increment(int &a)
{
    a++;
}

int main()
{
    int x = 5;
    increment(x);
    cout << x << endl; // Output: 6
    return 0;
}

Output

6

Difference Between Call by Value & Call by Reference in C++

S.No.Call by ValueCall by Reference
1A copy of the argument’s value is passed to the function.A reference to the argument is passed to the function.
2Changes made to the argument within the function are not reflected in the caller.Changes made to the argument within the function are reflected in the caller.
3The original argument remains unchanged.The original argument can be modified.
4A new memory location is allocated for the argument in the function.The argument in the function refers to the same memory location as the original argument.
5Typically used when you don’t want the function to modify the original argument.Typically used when you want the function to modify the original argument.

Note: When passing an argument by reference, you must use the & operator to indicate that you are passing a reference, rather than a copy of the argument.

We hope this article helped you to understand about C++ Call by Value & Call by Reference in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.