capypad
0 day streak
cpp / beginner
Snippet

References: Aliases for Variables

A reference is an alias that refers to the same variable. When you pass a variable to a function with a reference parameter (&), changes inside the function affect the original variable. This is different from pass-by-value where a copy is made. References are safer than pointers but serve a similar purpose.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
#include <iostream>
void doubleValue(int& num) {
num = num * 2;
}
int main() {
int value = 5;
doubleValue(value);
std::cout << "Value is now: " << value << std::endl;
return 0;
}
Breakdown
1
void doubleValue(int& num)
Function with reference parameter - changes affect the original variable
2
num = num * 2
Modifies the original variable directly through the reference
3
int& num
The ampersand (&) in the parameter type makes it a reference