Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Pass by Reference?
3.
Example 
3.1.
C++
4.
Swap Function using Pass by Reference
4.1.
C++
5.
Pass by Reference with Pointers
5.1.
C++
6.
Frequently Asked Questions
6.1.
What happens if you forget to use the '&' operator in a function parameter that is supposed to modify the variable?
6.2.
Can pass by reference improve the performance of my program?
6.3.
Is it safe to use pass by reference for all types of data in C++?
7.
Conclusion
Last Updated: Jun 11, 2024
Easy

Call by Reference in C++

Author Riya Singh
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In C++, there are two ways to pass arguments to a function: pass by value & pass by reference. Pass by reference allows a function to modify the original value of the passed argument. It works by passing the memory address of the variable instead of its value. This is useful when you need a function to change the value of the argument & have that change reflected in the original variable. 

Call by Reference in C++

In this article, we'll learn what pass by reference is, how it works with the help of examples, & cover some key points about using it effectively in your C++ programs.

What is Pass by Reference?

Pass by reference is a way to pass arguments to a function where the memory address of the variable is passed instead of its value. This means that any changes made to the argument inside the function will affect the original variable outside the function.

When you pass an argument by reference, you essentially create an alias or alternate name for the original variable. The function can then use this reference to access & modify the original variable directly.

To pass an argument by reference in C++, you need to use the ampersand (&) symbol before the argument name in the function declaration & definition. This tells the compiler that you want to pass the argument by reference instead of by value.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example 

Consider a function that takes two integer arguments & swaps their values:

  • C++

C++

#include <iostream>
using namespace std;
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}

int main() {
int x = 5;
int y = 10;

cout << "Before swap: x = " << x << ", y = " << y << endl;

swap(x, y);

cout << "After swap: x = " << x << ", y = " << y << endl;

return 0;
}

Output:

Before swap: x = 5, y = 10
After swap: x = 10, y = 5


In this example, the swap function takes two integer arguments a & b by reference. Inside the function, we use a temporary variable temp to store the value of a, then assign the value of b to a, & finally assign the value of temp to b. This effectively swaps the values of a & b.

When we call the swap function with x & y as arguments, the function modifies the original values of x & y directly. After the function call, the values of x & y are swapped, as evident from the output.

Note : This example shows how pass by reference allows a function to modify the original values of the arguments passed to it. The changes made inside the function are reflected in the original variables in the calling code.

Swap Function using Pass by Reference

In this example, we'll create a dedicated swap function that takes two arguments by reference & swaps their values.

  • C++

C++

#include <iostream>
using namespace std;
void swap(int& a, int& b) {

   int temp = a;

   a = b;

   b = temp;

}

int main() {

   int num1 = 10;

   int num2 = 20; 

   cout << "Before swap:" << endl;

   cout << "num1 = " << num1 << ", num2 = " << num2 << endl;

   swap(num1, num2);

   cout << "After swap:" << endl;

   cout << "num1 = " << num1 << ", num2 = " << num2 << endl;

  

   return 0;

}

Output:

Before swap:
num1 = 10, num2 = 20
After swap:
num1 = 20, num2 = 10


In this example, we define the swap function that takes two integer arguments a & b by reference. The function swaps the values of a & b using a temporary variable temp.

In the main function, we declare two integer variables num1 & num2 & initialize them with the values 10 & 20, respectively. We print their initial values using cout.

Then, we call the swap function, passing num1 & num2 as arguments. Since the arguments are passed by reference, the swap function directly modifies the values of num1 & num2.

After the function call, we print the values of num1 & num2 again using cout. We can see that the values have been swapped, with num1 now being 20 & num2 being 10.

Note : This example showcases how pass by reference allows a function to modify the original values of the arguments passed to it. By passing the arguments by reference, we can create functions that have side effects & can change the state of variables outside their scope.

Pass by Reference with Pointers

In C++, you can also achieve pass by reference using pointers. Pointers are variables that store the memory address of another variable. By passing a pointer to a function, you can indirectly modify the value of the variable it points to.

Here's an example that demonstrates pass by reference using pointers:

  • C++

C++

#include <iostream>
using namespace std;
// Write C++ code here
void updateValue(int* ptr) {
*ptr = 20; // Update the value at the memory address pointed by ptr
}

int main() {
int num = 10;

cout << "Before update: num = " << num << endl;

updateValue(&num); // Pass the address of num to the function

cout << "After update: num = " << num << endl;

return 0;
}

Output:

Before update: num = 10
After update: num = 20


In this example, we have a function called updateValue that takes a pointer to an integer (int*) as an argument. Inside the function, we dereference the pointer using the asterisk (*) operator to access & modify the value at the memory address it points to.

In the main function, we declare an integer variable num & initialize it with the value 10. We print its initial value using cout.

Then, we call the updateValue function, passing the address of num using the ampersand (&) operator. This means we are passing a pointer to num to the function.

Inside the updateValue function, the pointer ptr now points to the memory address of num. By dereferencing ptr & assigning a new value to *ptr, we are modifying the value of num indirectly.

After the function call, we print the value of num again using cout. We can see that the value of num has been updated to 20, even though we passed it to the function using a pointer.

Note : Pass by reference with pointers is a powerful technique that allows you to modify variables indirectly. It is commonly used when you need to modify multiple variables or when you want to avoid the overhead of copying large objects.

Frequently Asked Questions

What happens if you forget to use the '&' operator in a function parameter that is supposed to modify the variable?

If the '&' operator is omitted, the function will default to pass by value. This means any modifications made inside the function will only affect the local copy, not the original variable. The changes will not be reflected outside the function.

Can pass by reference improve the performance of my program?

Yes, pass by reference can significantly improve performance, especially in cases where large data structures or classes are involved. It eliminates the need for copying data, reducing memory usage and processing time.

Is it safe to use pass by reference for all types of data in C++?

While pass by reference is generally safe, it requires careful handling to avoid unintended side effects, such as accidentally modifying data. It's important to use const references when you want to ensure that the function does not alter the passed data.

Conclusion

In this article, we learned about pass by reference in C++. We discussed what pass by reference is & how it allows functions to modify the original values of arguments. We also looked at examples of using pass by reference to swap the values of variables & how to achieve pass by reference using pointers. Pass by reference is a powerful concept in C++ that enables functions to have side effects & modify variables outside their scope. It is a fundamental technique that every C++ programmer should learn and practice properly, which will eventually help them to solve more complex problems.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Previous article
Type Conversion in C++
Next article
C++ Operator
Live masterclass