Appendix R: References
CONTENTS:
Function Parameters: Pass By Reference
In C++, you can pass parameters to functions either by value or by reference. Passing by reference allows you to modify the original variable within the function.
The syntax is:
// pass by reference, note the single `&`
void functionName(<data_type> ¶meter_name)
{
// Function body
}
// pass by value, note the lack of single `&`
void functionName(<data_type> parameter_name)
{
// Function body
}
Example:
#include <iostream>
using namespace std;
// Function to increment a number by value
void incrementByValue(int num)
{
num++;
}
// Function to increment a number by reference
void incrementByReference(int &num)
{
num++;
}
int main()
{
int x = 5;
cout << "Before increment: " << x << endl;
incrementByValue(x); // passing x by value
cout << "After increment: " << x << endl;
cout << "---" << endl;
cout << "Before increment: " << x << endl;
incrementByReference(x); // passing x by reference
cout << "After increment: " << x << endl;
return 0;
}
Key points to remember:
- Parameters passed by reference are indicated by `&` in the function declaration.
- Changes made to the reference parameter within the function affect the original variable.
- Pass by reference avoids unnecessary copying of the argument to the parameter variable, which can be more efficient.
- Arrays are passed by reference by default (so there is no preceding `&` for an array parameter).
- References cannot be reassigned to refer to a different variable once initialized.