References
This lesson will show you how you can access variables indirectly with references.
Motivations
Let's say that you have a function that doubles the parameter.
#include <iostream>
void double_number(int num)
{
num = num * 2;
}
int main()
{
int x = 5;
double_number(x);
std::cout << x;
}
5
But this will not work,
because only the value of x
is written into num
.
This is where references come into play.
Using references
You can create a reference by adding a &
to the type of the variable you want to refer to.
int var = 5;
int& ref = var; // ref is a int reference that refers to var
Now, if you modify ref
, var
will also be modified because ref
is var
.
ref = 23;
std::cout << var; // Prints out 23
Pass by reference
Now let's see how we can use references to solve our issue.
We just need to make the function take a int reference
instead of int
.
#include <iostream>
void double_number(int &num)
{
num = num * 2;
}
int main()
{
int x = 5;
double_number(x);
}
10
Now the the function double_number
takes a reference,
num
will become whatever variable is passed into the function.
This means when we modify num (which has become x
), we also indirectly modify x
.
Modifying elements in a range-based for loop
A similar problem can be seen in range-based for loops. Since references become the variable that it is referring to, we can use it to access the elements in our arrays.
Here is a simple array
std::vector<int> arr = {2, 4, 6};
Let's say we want to add 5 to each element,
It's possible to do that one by one, but it becomes annoying and long if the array is big.
So loops will come to our rescue!
for (int x : arr)
{
x = x + 5;
}
std::cout << arr[0];
2
But the code above will unfortunately not work.
This is because only the value of the element is being copied into x
,
not the element itself.
This is where we can use references,
they can make the actual element of the array be copied into x
.
for (int& x : arr)
{
x = x + 5;
}
std::cout << arr[0];
7
Now each each element of the array has successfully increased by five.
You should only use references for when you actually need to modify the variable. Don't use references if you just need the value.