Lesson 21 - 25-1-13
Lesson 21 - 25-1-13
In this lesson, we will discuss reference parameters in C++, explain what they are, and
differentiate them from value parameters.
Reference Parameters vs Value Parameters
● On the other hand, when a variable is passed by value, a copy of the variable's value is
created, and the function operates on this copy. This means that the function cannot
modify the original variable's value.
Syntax
Reference parameters are denoted by an ampersand (&) placed after the parameter type in the
function declaration.
Diagram
Using reference parameters, we can create a function to swap the values of two variables:
Example 2: Updating a Counter
Reference parameters can be used to update the value of a counter variable:
Example 3: Finding the Maximum and
Minimum
We can use reference parameters to find the maximum and minimum values of an array:
Some notes on reference parameters.
● Reference parameters must be initialized with an existing variable when they are passed
to a function.
● Any changes made to a reference parameter within the function will be reflected in the
original variable outside of the function.
● Reference parameters can be used to return multiple values from a function, by modifying
the variables passed in.
In general, reference parameters are a powerful feature of C++ that can help simplify code and
reduce the need for copying large amounts of data. However, they should be used with care to
avoid unintended side effects and make code more readable.
Exercises
1. Write a function void updateCoordinates(int &x, int &y) that increments both x and y by 1.
Test your function with appropriate inputs and print the updated values.
2. Write a function void reverseSign(int &number) that reverses the sign of the given number.
Test your function with appropriate inputs and print the updated value.
3. Write a function void sortTwoNumbers(int &a, int &b) that sorts two numbers in ascending
order using reference parameters. Test your function with appropriate inputs and print
the sorted values.
Exercise 1 solution
Exercise 2 solution
Exercise 3 solution