A reference is an alias for another variable. It refers to the same memory location.
int original = 100;
int& ref = original;
ref = 200;
cout << original; // 200Both variables refer to the same value in memory. So if one changes the other changes as well
Use the ampersand & after the type to declare a reference:
int a = 5;
int& alias = a;You can pass references to functions to avoid copying:
void modify(int& x) {
x = 99;
}
int n = 10;
modify(n);
cout << n; // 99Unlike pointers, references cannot be reassigned to another variable once set.
int a = 5, b = 10;
int* p = &a; // pointer can be reassigned
p = &b;
int& r = a;
// r = b; ← modifies a, does not rebind the referenceUse const to prevent modification:
void print(const int& value) {
cout << value;
}Commonly used for read-only access to large data like strings or vectors.
Ask the AI if you need help understanding or want to dive deeper in any topic