Topic 45 of 83
References
Overview
A reference `&` is an alias (an alternative name) for an existing variable. While pointers hold memory addresses and can be manipulated, references are simpler, safer, and cleaner syntax-wise.
Syntax
cpp
int x = 10;
// Pointer
int* ptr = &x;
*ptr = 20;
// Reference
int& ref = x;
ref = 30; // x is now 30 (no * needed)Common Pitfalls
- Returning a reference to a local variable from a function. The variable dies when the function ends, leaving a dangling reference.
Interview Tips
- Know the 3 key differences: 1) References must be initialized immediately, pointers don't. 2) References cannot be null, pointers can. 3) References cannot be reassigned to alias a different variable later, pointers can be reassigned.
- Prefer references over pointers for function parameters unless you explicitly need 'null' as a valid state.
Real-World Example
Comparing syntax for modifying variables in a function.
example
cpp
#include <iostream>
using namespace std;
// Ugly pointer syntax
void incrementPtr(int* p) {
if (p != nullptr) (*p)++;
}
// Clean reference syntax
void incrementRef(int& r) {
r++;
}
int main() {
int a = 5, b = 5;
incrementPtr(&a);
incrementRef(b);
cout << "a: " << a << ", b: " << b << endl;
return 0;
}