I had a slight misconception about it at first, but I understand it well now. I'll show the first way you learn to pass data with a function
1 2 3 4
|
void A_function(int x)
{
x = 12;
}
|
In this function, when you pass a variable in, you aren't actually changing that variable, it's creating a copy of that variable, then when we use
x = 12;
we are setting the copy equal to 12. Sometimes you might want this, but other times you might not. So instead of passing by value, we have passing by reference.
1 2 3 4
|
void Another_function(int &x)
{
x = 12;
}
|
The & in the parameter means we will be directly accessing the variable passed in since we will be throwing in the memory address.
Look at the functions applied
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include<iostream>
void A_function(int x)
{
x = 12;
}
void Another_function(int &x)
{
x = 12;
}
int main()
{
int a = 1;
int b = 1;
A_function(a);
Another_function(b);
std::cout << a << std::endl;
std::cout << b << std::endl;
}
|
Compile that in your IDE and notice that
int a
did not change because it was passed by value, but
int b
did, since we directly accessed it by using passing by reference.