capypad
0 day streak
cpp / beginner
Snippet

References: Aliases for Variables

References are aliases that refer to the same memory location as another variable. Unlike pointers, references must be initialized and cannot be reassigned. They provide a clean syntax for passing variables to functions by reference.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
 
void doubleValue(int& ref) {
ref = ref * 2;
}
 
int main() {
int original = 10;
int& alias = original;
alias = 25;
std::cout << "Original: " << original << std::endl;
doubleValue(original);
std::cout << "After doubling: " << original << std::endl;
return 0;
}
Breakdown
1
int& alias = original;
Creates a reference alias pointing to original variable
2
alias = 25;
Modifying alias also changes original (both point to same memory)
3
void doubleValue(int& ref)
Function parameter is a reference, modifies original directly
4
ref = ref * 2;
Modifies the original variable through the reference