Passing parameters by reference lets a function change the original value of a variable. This saves memory and can make programs faster.
0
0
Passing parameters by reference in C++
Introduction
When you want a function to update the original variable, like changing a score in a game.
When you want to avoid copying large data, like big lists or objects, to save memory.
When you want multiple outputs from a function by changing several variables.
When you want to improve performance by not copying data unnecessarily.
Syntax
C++
void functionName(type ¶meterName) { // code that uses parameterName }
The ampersand (&) after the type means the parameter is passed by reference.
Changes to the parameter inside the function affect the original variable.
Examples
This function adds 1 to the original integer passed in.
C++
void increase(int &num) { num = num + 1; }
This function swaps the values of two integers by reference.
C++
void swap(int &a, int &b) { int temp = a; a = b; b = temp; }
Sample Program
This program shows how the function addFive changes the original variable value by adding 5 to it.
C++
#include <iostream> using namespace std; void addFive(int &number) { number += 5; } int main() { int value = 10; cout << "Before: " << value << endl; addFive(value); cout << "After: " << value << endl; return 0; }
OutputSuccess
Important Notes
Passing by reference allows the function to modify the original variable directly.
Be careful: changes inside the function affect the original data.
If you don't want the function to change the variable, use const reference.
Summary
Passing parameters by reference lets functions change original variables.
Use & after the type in the function parameter to pass by reference.
This method saves memory and can improve performance.