Topic 9: Functions (Pass by Reference)

In C++, functions can be used to pass data by reference, allowing the function to modify the actual argument passed. This is in contrast to passing by value, where a copy of the argument is made.

When passing by reference, the function works with the original variable, so any changes made inside the function are reflected outside the function as well. This is achieved using reference parameters in the function definition.

Advantages of Passing by Reference

  • Efficient: No copying of arguments, which can save time and memory.
  • Allows modification: The function can modify the actual arguments, enabling multiple return values.

Defining a Function with Reference Parameters

To define a function with reference parameters, use the ampersand (&) after the data type in the parameter list. Here’s an example:

Example: Swap Two Numbers
  • 
    void swap(int &a, int &b) {
        int temp = a;
        a = b;
        b = temp;
    }
                                        

In this example, the swap function takes two reference parameters, a and b. When called, it swaps the values of the two variables passed to it.

Calling a Function with Reference Parameters

To call a function with reference parameters, simply pass the variables as you would for a normal function:

Example: Calling the Swap Function
  • 
    int main() {
        int x = 10;
        int y = 20;
    
        cout << "Before swap: x = " << x << ", y = " << y << endl;
    
        swap(x, y);
    
        cout << "After swap: x = " << x << ", y = " << y << endl;
    
        return 0;
    }
                                        

In this example, the main function calls swap with x and y. Before the call, x is 10 and y is 20. After the call, x is 20 and y is 10.

Reference vs. Pointer Parameters

Reference parameters are similar to pointer parameters but have some key differences:

  • Syntax: Reference parameters use the & symbol, while pointer parameters use *.
  • Usage: References are usually simpler and safer to use as they do not require dereferencing.