Previously we’ve seen how variables are passed by value. While this works well in many cases, it means that the variable has to be duplicated when it is passed to the function. For large, and/or complicated, variables – like when we start using objects, this can take precious time and resources.
However, C++ offers us a way to not have that problem. To pass the variables by reference. This means we actually use the exact same variables in both the calling and the called function.
When you pass a variable by reference, you are actually passing the memory address, so it uses the same variable. This is much faster than creating a new variable and copying the data.
Additionally, it allows changes in the function to get passed back to the calling function. This is a work around for the face that C++ functions can only return a single value.
To define a variable by reference, in the parameter you can use any of the following:
dataType &refVariable; // I find this to be the most common
dataType & refVariable;
dataType& refVariable;
Place this in your parameter list and it will work like a regular variable.
void updateVariables(int num1, int &num2);
int main()
{
int num1 = 0;
int num2 = 0;
cout << "num1: " << num1 << " num2: " << num2 << endl;
updateVariables(num1, num2);
cout << "num1: " << num1 << " num2: " << num2 << endl;
updateVariables(num1, num2);
cout << "num1: " << num1 << " num2: " << num2 << endl;
updateVariables(num1, num2);
cout << "num1: " << num1 << " num2: " << num2 << endl;
}
void updateVariables(int x, int &y)
{
x++; // passed by value so main variable is not updating
y++; // passed by reference, will update variable in main function
}
Passing Arguments by Reference was originally found on Access 2 Learn
One Comment
Comments are closed.