1. Home
  2. >
  3. C++
  4. >
  5. Difference Between Call by...

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

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

Have a look at this program:

#include<iostream>
 
// function to multiply by 5
void multiplyByFive(int num){
  num *= 5;     //num = num * 5
}
// Main function
int main() {
  int x = 2;
  multiplyByFive(x);  // calling the function
  std::cout << x;    
  return 0;
}

We are trying to multiply the variable “num” by 5. According to you, what would be the output of the above C++ program? Is it 10? Did you find any errors in the program?

If your answer to the above question was 2, congratulations, your answer is correct! And if your answer was 10, bear with us. We are going to explore more about the reason behind this. 

As a beginner C++ programmer, one of the first topics I came across was pass-by-reference and pass-by-value. I still remember the lecture when I was first introduced to this topic. 

Teacher: Good morning, class! Please log in to your PCs and write a C++ function to multiply a value by 5.

Me: *wrote the same code as above* 

Me: Sir, can you please help me with this code? I am not very sure why I am not getting the expected output. I am calling this function to update the value of my variables, but I see no effect.

Teacher: This is because of pass by value and pass by reference… *some arrows, numbers, and random memory block diagrams on the whiteboard*… and on and on.

Sir: I hope you have understood this.

Me (scrounging youtube to search for a better explanation): Of course, sir. I got you. 

While I suffered for an explanation, this article will walk you through the concept of call by value vs. call by reference in detail. We have covered examples to help you better understand each of the concepts. And at the end, we have drawn a comparison between both concepts to present a clearer picture for you.

So, before diving into the actual concept, let’s revise what a function means. 

A function is a group of statements that takes input, processes it, and returns an output. In other words, a function is a reusable chunk of code that can perform a given task. Consider the first example, it contains the following code:

 // function to multiply by 5
void multiplyByFive(int num){
  num *= 5;     //num = num * 5
}

This bit of code is known as a function. And it performs the task of multiplying a value (num in this case) by 5.

The value (variable x in this case) that is passed in the function multiplyByFive()from main() is called the actual parameter. And the value (variable num in this case) received by multiplyByFive() is called the formal parameter.

For a function to perform the specified task, it must be called. And in C++, a function can be called in two ways:

  1. Pass by Value, also known as Call by Value
  2. Pass by Reference, also known as Call by Reference

There is a subtle difference between call by value and call by reference. Both differ by the type of values that are passed to them as parameters.

difference between call by value and call by reference in C++

Pass by value means a copy of the actual value is passed on. Pass by reference means an address (reference) is passed, which defines where the value is stored. Let’s discuss both of them in detail.

Pass by Value in C++

Pass-by-value is also known as pass-by-copy or call-by-value. By definition, pass-by-value means to pass in the actual parameter’s copy in memory as the formal parameters.

To say it in simpler terms, let’s understand what happens when we pass a value to a function via pass-by-value:  

  • We pass in the actual parameters.
  • A copy of the same is created in the memory.
  • This copy is passed as the formal parameters.

Now since we are passing a copy, both the parameters are stored in different memory locations. And thus, any change inside the function will not have any effect on the original values. 

Example:

#include <iostream>
 
// function to swap two values
void swap(int a, int b)
{
   int temp;
 
   temp = a;
   a = b;
   b = temp;
 
}
 
// main function
int main()
{
   int x = 5, y = 15;
 
   // pass by values
   swap(x, y);
   std::cout << "x:" << x << ", y:" << y;
 
   return 0;
}

Output:

x: 5, y: 15

The above function aims to swap the values of the variables x and y. However, we did not see any change in the values. This is because all the changes are made in the dummy variables (a and b in this case) that are stored at a different memory location.

difference between pass by value and pass by reference

Recall the program to multiply a number by 5 that we first encountered. Were you now able to reason the logic behind the unexpected answer? Give it a try! You know the answer.

When to use Pass by Value in C++?

  • When we want to perform calculations without changing the original values.
  • While multithreading to prevent the values from changing via any other thread. Multithreading in simple words is running two or more parts of a program concurrently.  

What are the Advantages of Pass by Value in C++?

  • Functions are free to modify the passed values without affecting the original data.
  • Great while working with multithreaded or asynchronous programs where we need to keep track of the values.
  • Pass by value method can be used to convert a string from an integer without modifying its value.

What are the Disadvantages of Pass by Value in C++?

  • Since pass by value is implemented by passing a copy of the data, the data size increases (doubles). This may not be an issue with smaller programs but can cost efficiency in larger programs. 
  • If the argument is too large, copying the values can take a significant amount of time.
  • There is no way to propagate back the updated values through the parameters.

Pass by Reference in C++

Pass-by-reference is also known as pass-by-address or call-by-reference. While calling a function, instead of passing the values of variables, we pass a reference to values.

Let’s understand the flow:

  • We pass in the actual parameters.
  • A reference variable is created and passed to the function.

A reference variable is a nickname for any variable. 

Now since we are passing a copy of the address, both the variables point to the same value. And thus, any change in the function would be reflected in the actual values.

Example:

#include <iostream>
 
// function to swap values
void swap(int* a, int* b)
{
   int temp;
 
   temp = *a;
   *a = *b;
   *b = temp;
 
}
 
// main function
int main()
{
   int x = 5, y = 15;
 
   //pass by reference
   swap(&x, &y);
   std::cout << "x:" << x << ", y:" <<y;
 
   return 0;
}

Output:

x: 15, y: 5

In the above C++ program, both the actual and the formal parameters point to the same memory location. In other words, both x and a are aliases of the same memory location. The same goes for y and b. Thus, all the changes made in the swap() function are evident in the original values.

The variables a and b contain the address of x and y respectively.

Notice we are using & when calling the function. It is used to denote that an address is passed through the parameters. 

In the function definition, we are using * (dereferencing variable) to access the value at the given memory location. This means that we can access the values stored at x (5) and y (15) using *a and *b respectively. In simpler terms, *a = 5 and *b = 15.

pass by value vs pass by reference

Note that if we fail to use the dereferencing operator, we might encounter an error saying, assigning to ‘int’ from incompatible type ‘int*’; dereference with *, which means that we cannot assign int* to int.   

Now let’s recall the very first example that we encountered. Can you now tweak it to produce the expected answer, 10? Here is how you can do it: 

#include<iostream>
 
// function to multiply by 5
void multiplyByFive(int* num){
  (*num) *= 5;     //num = num * 5
}
 
// Main function
int main() {
  int x = 2;
  multiplyByFive(&x);  // pass by reference
  std::cout << x;    
  return 0;
}

The output of this program would be 10. Here, we have only changed the method of passing the values and not any variable name. 

When to use Pass by Reference in C++?

  • When we are changing the parameters passed by the client program.
  • When passing large structures and classes to make the program efficient.
  • To avoid copying the values and reducing the space complexity. 

What are the Advantages of Pass by Reference in C++?

  • We can produce efficient programs since no copy of the data is made.
  • It enhances the ease of exchanging the information between functions through the use of parameters. 

What are the Disadvantages of Pass by Reference in C++?

  • This method is not recommended while developing multithreaded programs since it can cause loss of data.
  • Being a high-level mechanism, pass by reference can only be used within a single program. 
call by value vs call by reference

Pass by Value vs Pass by Reference in C++

Pass by ValuePass by Reference
Also known as pass by copy and call by value.Also known as pass by address and call by reference.
Copies of the original values are passed to the function.Only a reference variable (alias name) is passed to the function.
Any change in the function will not be reflected in the original values.Every change in values is reflected in the actual values. 
Values are passed just like it’s done for any program.Pointer variables are passed to refer to the address location. 

Conclusion

In this article, we have discussed in detail about pass by value and pass by reference. Given below are the takeaways from this article:

  • There are two ways to pass a value to a function: pass by value and pass by reference. 
  • In pass by value, a copy of the original values is passed to the function.
  • In pass by reference, a reference to the variable is passed to the function.
  • Both pass by value and pass by reference have their own sets of advantages and disadvantages. Using both of them depends on the requirements of the program. 
  • We have also drawn a comparison between both methods to help you better understand the concepts.    
Shubham Gautam
+ posts

I'm an MLH Fellow & a Google DSC Lead. I love both technology and creative writing, and thus to cherish my love for both.