References as Parameters
Lesson 9 of 14 in Coddy's C++ Pointers course.
Now, we can see how we're able to make work easier by using references as arguments when calling functions.
If we go back to the lesson for passing pointers as parameters we mentioned how when we pass values to a function, the values we operate within the function are copies of the original values we passed.
We used pointers to solve this problem, but instead of using addresses, dereferencing, pointers, etc. We can just mark the parameters we take as references and do our normal work as we would with regular values
// Instead of this
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
cout << *x << " " << *y << endl;
}
// We can do this
void swap(int &x, int &y) {
int temp = x;
x = y;
y = temp;
cout << x << " " << y << endl;
}Now, if we call the swap() function the values of the two integers we pass will permanently be changed. So, instead of taking the memory addresses of the values, and changing the values at those memory addresses by dereferencing them, we just take references to the actual values as arguments and we do the work on those. Because they refer to the original values, any change is permanent
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyFinish the function Calculator from two lessons ago, but instead of using pointers, use references to the values of the variables large and small. In the function, subtract large by the difference between large and small, and add small to itself.
Input
5 3
Output
5 3
3 6
Explanation
Subtracting 5 by the difference between 5 and 3 which is 2, is 5 - 2 = 3, while adding 3 to 3 gives us 6
Note: Do NOT write the main() function
Try it yourself
#include <iostream>
using namespace std;
void Calculator(// Take arguments: large & small as references) {
// Enter code for calculations
}
// Do NOT write the main() functionAll lessons in C++ Pointers
2Pointers & References
Pointers as ParametersReferences - &References as ParametersPointers vs References