Test One:
#include <iostream>
void function(int ¶meter);
int main()
{
int variableOne = 0;
int variableTwo = 6;
function(variableOne);
std::cout << variableOne << std::endl;
function(variableTwo);
std::cout << variableTwo << std::endl;
return 0;
}
void function(int ¶meter) // ???
{
parameter += 5;
}
Test Two:
#include <iostream>
int main()
{
int variableOne = 2;
int variableThree = 7;
int &variableTwo = variableOne;
std::cout << variableOne << std::endl;
&variableTwo = variableThree; // ERROR (wrong side of operand etc...)
std::cout << variableThree << std::endl;
return 0;
}
1) So why is it that ¶meter can be assigned the value (of the arguments) multiple times, (test one) but &variableTwo (test two) cannot be?
2) Is this because, (test one) the memory address of parameter is assigned to variableOne and variableTwo? Or, does the value of variableOne get assigned to parameter, then variableTwo later on?
3) Perhaps, is it that a new instance of parameter is created each time the function is called?
When you call
functionwith different arguments you’re creating a new reference to the argument upon each invocation.Here you’re trying to assign the value of
variableThreeto the address ofvariableTwo, which is illegal (and doesn’t make sense either).Moreover, references cannot be reseated after being created. So, even the following is illegal.
Note that the same rule applies to the function as well. If you were to try and reassign the input parameter to refer to some other integer the code wouldn’t compile.