Table of Contents
Passing by reference allows a function parameter to refer directly to an object supplied by the caller. Unlike passing by value, no separate copy of the argument is created. Changes made through the reference therefore affect the original variable.
A reference parameter is declared by placing & after the parameter’s type. This mechanism is commonly used when a function needs to modify the caller’s object or when copying a large object should be avoided.
Source Code #
#include <iostream>
void updateValue(int& value)
{
value = 100;
}
int main()
{
int number = 50;
updateValue(number);
std::cout << "Number: " << number << '\n';
return 0;
}
Output #
Number: 100
Explanation #
int& valuedeclaresvalueas a reference parameter.updateValue(number)passes the variablenumberto the function.- The reference parameter
valuerefers directly to the originalnumberobject. value = 100;therefore modifies the original variable rather than a copy.- After
updateValue()returns,numbercontains100. - Passing by reference allows a function to modify an object supplied by the caller.
- A reference parameter must be initialized with a valid object when the function is called.
- Passing by reference can also avoid copying large objects, which can improve efficiency.