You met references in the Functions module. A reference is another name for an existing variable:
#include <iostream>
using namespace std;
int main() {
int original = 10;
int& nickname = original; // nickname IS original
nickname = 20;
cout << original << "\n";
return 0;
}Output
20
Side by side
Reference int& r = x; | Pointer int* p = &x; | |
|---|---|---|
| Use the value | r | *p |
| Can be empty? | No – always refers to something | Yes – nullptr |
| Can switch to another variable? | No | Yes |
| Must be set when created? | Yes | No (but you should!) |
Functions with pointer parameters
Both let a function change the caller's variable. With a pointer the caller passes an address:
#include <iostream>
using namespace std;
void doubleIt(int* n) {
*n = *n * 2;
}
void tripleIt(int& n) {
n = n * 3;
}
int main() {
int value = 5;
doubleIt(&value); // pass the address
cout << value << "\n";
tripleIt(value); // pass the variable itself
cout << value << "\n";
return 0;
}Output
10 30
Remember: Prefer references – they are simpler and can't be null. Use pointers when something might be “nothing” (
nullptr), or must point to different things over time.