cpp / beginner
Snippet
References: Aliases for Variables
A reference is an alias for an existing variable. Declared with &, it must be initialized when created and cannot be changed to reference something else. Any modification through the reference affects the original variable. References provide an alternative way to access variables without copying.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>int main() {int original = 100;int& ref = original;ref = 200;std::cout << "Original: " << original << std::endl;std::cout << "Reference: " << ref << std::endl;return 0;}
Breakdown
1
int& ref = original;
Creates a reference that refers to the same memory location as original
2
ref = 200;
Modifies the value through the reference; original also changes since they share memory