In C++, passing arguments by reference allows a function to access and modify the original values of variables. Unlike passing by value (where a copy of the argument is made), passing by reference uses the actual memory location of the variable. This is particularly useful for:
This example demonstrates how to pass arguments by reference, allowing a function to modify the calling variables directly.
#include <iostream>
// Function to swap two numbers by reference
void swap(int& a, int& b) {
int temp = a; // Save the value of a in temp
a = b; // Assign b to a
b = temp; // Assign temp (original a) to b
}
int main() {
int num1 = 10, num2 = 20;
std::cout << "Before swapping: num1 = " << num1 << ", num2 = " << num2 << std::endl;
// Passing arguments by reference
swap(num1, num2);
std::cout << "After swapping: num1 = " << num1 << ", num2 = " << num2 << std::endl;
return 0;
}
swap Function:
swap(int& a, int& b) takes two references as arguments.int temp = a; saves the value of a.a = b; assigns the value of b to a.b = temp; assigns the saved value of a to b, effectively swapping the two values.main()
swap(num1, num2); → Passes the actual variables num1 and num2 by reference to the function.num1 and num2 directly.Before swapping: num1 = 10, num2 = 20
After swapping: num1 = 20, num2 = 10
In this example, passing by reference allows the swap function to modify the values of num1 and num2 directly in the main() function, making it a more efficient and flexible way to handle data.