Call By Value And Call By Reference In C++ - C++ Programming Tutorial
C++ Course / Pointers & References / Call By Value And Call By Reference In C++

Call By Value And Call By Reference In C++

BLUF: Mastering Call By Value And Call By Reference In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Call By Value And Call By Reference In C++

C++ is renowned for its efficiency. Learn how Call By Value And Call By Reference In C++ enables low-level control and high-performance computing in the tutorial below.

In C++, there exist primarily two techniques employed for transferring arguments to a function: Call by Value and Call by Reference. These approaches delineate the manner in which data is transferred to functions and how modifications to the data are managed.

In the call-by-value approach, the original value remains unchanged, whereas it can be altered in the call-by-reference method. Now, let's explore call by value and call by reference in the C++ programming language separately.

Call by Value in C++

In the call-by-value approach, the initial value of the parameter is typically transmitted to the function. This technique allows us to duplicate the original parameter into a formal parameter. The call-by-value mechanism operates on this duplicated argument, preserving the original data from any modifications.

If there is a need to alter the value of a function parameter, the modification is limited to the current function scope. This implies that any adjustments made within the parameter do not impact the original variables.

Syntax

It has the following syntax:

Example

return_type function_name(data_type parameter1, data_type parameter2, ...);

C++ Call by Value Example

Let's consider an example to demonstrate the concept of Call by Value in C++.

Example

Example

#include <iostream>  

using namespace std;  

void change(int data);  

int main()  

{  

int data = 8;  

change(data);  

cout << "The value of the data is: " << data<< endl;  

return 0;  

}  

void change(int data)  

{  

data = 6;  

}

Output:

Output

The value of the data is: 8

Explanation:

In this instance, the data is set to 8 during the initialization within the main function. Subsequently, the change function is invoked with data as a parameter; however, as this function is passed by value, only a replica is altered within the change function. Finally, the value of the data is displayed.

Call by Reference in C++

In C++, pass by reference is a technique utilized to transfer values to function parameters. This approach allows the function to alter the original variable's value directly as both formal and actual parameters point to the same variable. Any modifications within the function's parameters will impact the initial arguments.

Note: In order to understand the call by reference, we must have basic knowledge of pointers.

C++ Call by Reference Example:

Let's consider an example to demonstrate the concept of Call by Reference in the C++ programming language.

Example

Example

#include<iostream>  

using namespace std;    

void swap(int *a, int *b)  

{  

 int swap;  

 swap=*a;  

 *a=*b;  

 *b=swap;  

}  

int main()   

{    

 int a=200, y=80;    

 swap(&a, &b);  // Here, passing value to function  

 cout<<"The value of a is: "<<x<<endl;  

 cout<<"The value of b is: "<<y<<endl;  

 return 0;  

}

Output:

Output

The value of a is: 80

The value of b is: 200

Explanation:

In this instance, we are examining the swap function which accepts two pointers int a and int b. Within the swap function, the values are interchanged by utilizing a temporary variable named swap. Subsequently, the initial variables within the main function undergo modification as the function interacts directly with their memory addresses via pointers.

When to use Call by Value and Call by Reference in C++

There are various situations in which Call by Value and Call by Reference are employed in C++. A few examples include:

Call by Value:

Call by Value can be used when:

  • We don't need to modify the original parameters of the function.
  • We need to make copies of the data instead of the original data.
  • We don't deal with backtracking recursion.
  • Call by Reference:

Call by Reference can be used when:

  • We need to change the original variable value inside a function.
  • We work with large data because call by reference does not make a copy of the data.
  • We have a large object and wish to avoid the overhead of copying this object.
  • Advantages of Call by Value and Call by Reference:

There are numerous benefits of call by value and call by reference in C++. Some key advantages of these functions include:

Advantages of Call by Value:

  • Call by value does not modify the original variables.
  • Whenever this function is called, it does not affect the original value of the actual arguments.
  • It is useful for those functions that only require reading data because they cannot modify them.
  • There is no risk of memory leaks or dangling pointers because the copies are destroyed by default when the processing ends.
  • In this function, the value of the original argument is passed to the formal arguments. Therefore, any modification made to the formal parameters does not affect the original parameters.
  • Advantages of Call by Reference:

  • Call by reference modifies the value of the original values directly.
  • It is very useful for large data structures and for those who need modifications.
  • It helps us to avoid the modifications that occur by mistake.
  • It doesn't make duplicate data to store values that assist in saving memory space.
  • Disadvantages of Call by Value and Call by Reference:

There are various drawbacks associated with call by value and call by reference in C++. Some key disadvantages of these methods include:

Disadvantages of Call by Value:

Call by value is not suitable to update or change the original variable value.

  • Call by value is not suitable for updating or changing the original variable value.
  • It does not work effectively with dynamic memory allocation.
  • If a function is invoked too many times using Call by Value, new copies are made for each call, resulting in a stack overflow.
  • Disadvantages of Call by Reference:

  • As the function works with the original data in call by reference, accidental changes may modify the actual variables, which leads to unexpected errors.
  • If using pointers in the call by reference, passing nullptr by accident can raise runtime errors.
  • As the function is passed by reference, it is no longer pure theoretically.
  • When several references refer to the same data, changing one reference affects all of them.
  • Difference between call by value and call by reference in C++:

Some key variances between call by value and call by reference include:

Features Call by Value Call by Reference
Value Passed A copy of the value is passed to the function. An address of value is passed to the function.
Changes Changes made within the function are not reflected in other functions. Changes made with the function are reflected outside the function also.
Memory Location Actual and formal arguments will be created in different memory locations. Actual and formal arguments will be created in the same memory location.
Data Types It is suitable for basic and simple data types, including int, float, char, etc. It is suitable for complex data types, such as arrays, structs, strings, etc.
Performance It decreases the risk of unintentional side effects. It increases the risk of unintentional side effects.
It is faster than the call by reference because of the smaller data transfer. It can be slower because of the requirement to access data via references.

C++ Call by Value and Call by Reference MCQs:

  1. What is the right syntax for calling a function using call by value?
  • fun;
  • fun(x, y);
  • fun(x, y);
  • fun(&x, &y);
  1. What would happen when a function changes a variable passed by reference in C++?
  • The original value will be changed.
  • The program shows an error.
  • Only the local copy will be modified.
  • A new variable is created.

(a) The initial value is going to be altered.

  1. What is the expected result of executing the provided code snippet?
Example

#include <iostream>

using namespace std;

void modify(int &a) {

    a = 15;

}

int main() {

    int number = 7;

    modify(number);

    cout << "Number = " << number;

    return 0;

}
  • Compilation Error
  1. Which function is more efficient when passing the large objects as arguments?
  • Call by Reference
  • Call by Value
  • Both are equally efficient
  • None of the above
  1. Which of the following options is correct about the Call by Value in C++?
  • The actual variable is modified.
  • The function works directly with the actual memory location.
  • The actual variable remains unchanged.
  • None of the above.

(c) The original variable retains its value unaltered.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience