Call by Value in C++

In the call-by-value method, function arguments are passed by copying the value of the actual parameter, ensuring the original values remain unchanged. The value is copied to the formal parameter.

One is the original copy and the other is the function copy. Any changes made to the parameters within the function do not change the original values outside the function.

Example of Call by Value

The below example demonstrates the working of call by value by updating the original value of a variable.

C++




// C++ program to demonstrate call by value
  
#include <iostream>
using namespace std;
  
// function to update the original value
void increment(int num)
{
    num++;
    cout << num << endl;
}
  
int main()
{
    int number = 5;
    increment(number); // Passing 'number' by value
    cout << number << endl;
    return 0;
}


Output

6
5

Explanation: In the above program the “number” is passed as an actual parameter to the function increment and in the function as a formal parameter “num” that stores the value of “number”. In the function, the value of “num” is incremented but there is no change in the value of “number”. This is what we say “call by value”.

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

In C++ programming we have different ways to pass arguments to functions mainly by Call by Value and Call by Reference method. These two methods differ by the types of values passed through them as parameters.

Before we look into the call-by-value and call-by-reference methods, we first need to know what are actual and formal parameters.

The actual parameters also known as arguments are the parameters that are passed into the function when we make a function call whereas formal parameters are the parameters that we see in the function or method definition i.e. the parameters received by the function.

Similar Reads

Call by Value in C++

In the call-by-value method, function arguments are passed by copying the value of the actual parameter, ensuring the original values remain unchanged. The value is copied to the formal parameter....

Call by Reference in C++

...

Difference between the Call by Value and Call by Reference in C++

In the call-by-reference method, the memory address (reference) of the actual parameter is passed to the function, allowing direct access and modification of the original values. The actual and the formal parameters point to the same memory address. Any changes made to the parameters within the function are directly reflected in the original values outside the function....

Conclusion

...