Example
Consider a function that takes two integer arguments & swaps their values:
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;
}
You can also try this code with Online C++ Compiler
Run Code
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++
#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;
}
You can also try this code with Online C++ Compiler
Run Code
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++
#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;
}
You can also try this code with Online C++ Compiler
Run Code
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 DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.