Example 6: Pass Function Arguments by Reference

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:

  1. Modifying the original variables inside the function.
  2. Improving performance by avoiding copying large data structures (e.g., arrays, objects).
  3. Returning multiple values from a function without using pointers or complex data structures.

This example demonstrates how to pass arguments by reference, allowing a function to modify the calling variables directly.


Code Example

#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;
}

Explanation & Output

Code Breakdown:

  1. Defining the swap Function:
    • The function swap(int& a, int& b) takes two references as arguments.
    • In the function:
      • 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.
  2. Calling the Function in main()
    • swap(num1, num2); → Passes the actual variables num1 and num2 by reference to the function.
    • The function modifies num1 and num2 directly.

Expected Output:

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.