capypad
0 day streak
cpp / beginner
Snippet

References as Aliases

A reference is an alias (alternative name) for an existing variable. Unlike pointers, references cannot be null and must be initialized when created. Use the & symbol in both declaration and function parameters. When you modify a reference, you modify the original variable. References are safer than pointers and make code more readable.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
 
void doubleValue(int& ref) {
ref = ref * 2;
}
 
int main() {
int original = 10;
int& alias = original;
 
std::cout << "Original: " << original << std::endl;
std::cout << "Alias: " << alias << std::endl;
 
alias = 20;
std::cout << "After changing alias: " << original << std::endl;
 
doubleValue(original);
std::cout << "After doubleValue: " << original << std::endl;
 
return 0;
}
Breakdown
1
int& alias = original;
Creates reference alias that refers to original variable
2
alias = 20;
Modifying alias also changes original since they share memory
3
void doubleValue(int& ref) {
Reference parameter lets function modify caller's variable directly
4
ref = ref * 2;
Changes the original variable in main through the reference
5
doubleValue(original);
Passes original to function which doubles it through the reference