C++ References
A reference is an alias for an existing variable, declared with `&`, and once bound it cannot be reseated to refer to another variable. Modifying a reference modifies the original variable directly.
References are widely used as function parameters to avoid copying large objects and to allow a function to modify the caller's variable.
Declaring a reference
`int& ref = x;` makes ref another name for x. Any change to ref changes x, and vice versa, since they share the same memory location.
References in function parameters
`void increment(int& n) { n++; }` modifies the caller's variable directly, avoiding a copy and enabling 'pass by reference'.
int x = 5;
int& ref = x;
ref = 10;
std::cout << x;10Changing ref changes x since they refer to the same memory.
void addOne(int& n) { n++; }
int main() {
int x = 5;
addOne(x);
std::cout << x;
}6Passing by reference lets the function modify the original variable.
Key points
- A reference is an alias, declared with &.
- References cannot be null or reseated after binding.
- Pass-by-reference avoids copying and allows mutation.
- const int& is used to pass efficiently without allowing changes.
