I've been having a lot of trouble with truly understanding parameters and reference parameters in general. |
I'll go over these basics briefly. For now, I will
not discuss the difference between parameters and arguments, because at this point it might unnecessarly confuse you.
When you declare a variable, such as
int score
, space gets reserved somewhere in memory to hold the value of
score
.
You can think of memory as being a long list of sequentially placed slots to fill with values. Each "slot" has a unique address - It's kind of like house numbers. This means, that when you declare
int score
,
score
has a unique address in memory from which its value is modified or read.
When you pass a variable to a function, typically, you pass "by-value", which means a copy of the variable you've passed (parameter) is created, and the copy exists for the lifetime of the function. The original variable and it's copy both have different, unique addresses in memory, as you might expect.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
void function(int param) {
param = 20;
}
int main() {
int a = 10;
function(a);
std::cout << a << std::endl;
std::cin.get();
return 0;
}
|
In the code above, you have a function which takes one integer parameter, and assigns the value 20 to it. In your main() function, you have
int a
initialized with a value of 10. You call the previously mentioned function, and provide
a
as a parameter. Then you print
a
.
What gets printed? Ten or twenty?
"10" is printed, because we passed
a
by-value. A copy of
a
was made, and the copy was assigned a value of 20, while the original
a
remained unaltered.
In order to prevent the function from creating a copy of the original parameter, and instead, modify the original parameter, we need to pass by-reference.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
void function(int& param) {
param = 20;
}
int main() {
int a = 10;
function(a);
std::cout << a << std::endl;
std::cin.get();
return 0;
}
|
Note the ampersand(&) on line 3. It's the only change that has been introduced to the previous code. The function no longer creates a copy, and modifies the original variable. As a result, "20" is printed instead of "10".
In this case,
int& param
is a reference, because it refers to the address of
a
.