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.

Practice Questions

  1. How is passing by reference different from passing by value?
  2. In what scenario would passing by reference be preferred over passing by value for primitive data types (e.g., int, float)?
  3. What happens if you try to pass a literal value (e.g., 5) to a function that accepts a parameter by reference?
  4. What are the possible risks of using pass-by-reference?
  5. How can you prevent a function from modifying an argument passed by reference?
  6. How do references help in achieving performance optimization in C++ functions?
  1. Write a function swap(int &a, int &b) that takes two integers by reference and swaps their values.
    • Define the swap() function, which takes two integers by reference.
    • In main(), ask the user for two numbers, call the swap() function, and display the swapped values.
    • Ensure the original values are modified after the function call.
  2. Create a function calculate(int a, int b, int &sum, int &product) that takes two integers by value and returns their sum and product using reference parameters.
    • Pass sum and product by reference to store the results.
    • In main(), display the sum and product of the two numbers.
  3. Create a function findMax(int &a, int &b, int &c) that takes three integers by reference and finds the maximum value among them.
    • Pass three integers by reference.
    • Modify the largest value among the three to a reference variable max and print the result.
  4. Write a function calculateCircle(float radius, float &area, float &circumference) that takes the radius of a circle by value and calculates the area and circumference using reference parameters.
    • Pass area and circumference by reference.
    • Display the area and circumference in main().
  5. Create a function processString(string &input, int &length, int &sum) that calculates the length of the string and the sum of the ASCII values of all characters in the string using reference parameters.
    • Pass the string, length, and sum by reference.
    • Display the results in main().
    • Example if the string is "Hello" then the lenght is 5 and the sum of ASCII values is 500
  6. Write a function named time() that has an integer parameter named seconds and three integer reference parameters named hours, mins, and secs. The function is to convert the passed number of seconds into an equivalent number of hours, minutes, and seconds.
    • Using the reference parameters, the function should alter the arguments in the calling function.
    • Test the program by writing the main function.
  7. The viscosity and density of three common fluids are listed in the following chart:
    Book inventory
    Using this data, write and test a function named viscDen() that returns the viscosity and density of the selected fluid by using reference parameters. The type of fluid should be input to the function as a character that’s passed by value.
Coming Soon...