References and Pointers
A reference, written with &, is an alias for an existing variable — once bound, it can never be reassigned to refer to something else. Passing a reference into a function lets that function modify the original variable, without the overhead of copying it.
#include <iostream>
using namespace std;
void addOne(int& n) {
n = n + 1;
}
int main() {
int x = 5;
addOne(x);
cout << "x = " << x << endl;
return 0;
}x = 6
Pointers
A pointer, written with *, holds the memory address of a value rather than aliasing it directly. Unlike a reference, a pointer can be reassigned to point somewhere else entirely, and can be null (nullptr) to mean 'points at nothing'. & takes an address, * dereferences a pointer to get the value it points to.
#include <iostream>
using namespace std;
int main() {
int x = 10;
int* p = &x;
cout << "value = " << *p << endl;
*p = 20;
cout << "x = " << x << endl;
return 0;
}value = 10 x = 20
What a real const-correctness error looks like
Unlike Rust, C++ has no borrow checker tracking who can read or write a value at any given moment — but it does enforce const-correctness: a function that takes a const reference is promising not to modify what it refers to, and the compiler holds it to that promise. This is genuinely what g++ reports when that promise is broken — captured from a real run, not written to look plausible:
#include <iostream>
using namespace std;
void tryToModify(const int& n) {
n = 100;
}
int main() {
int x = 5;
tryToModify(x);
cout << x << endl;
return 0;
}main.cpp: In function ‘void tryToModify(const int&)’:
main.cpp:5:7: error: assignment of read-only reference ‘n’
5 | n = 100;
| ~~^~~~~Nothing runs at all — no output, just the error. const-correctness is one of the few compile-time guarantees C++ does give you for free; everything else about memory safety here is convention, not enforcement.
Next: functions and overloading — parameters, default arguments, and compile-time polymorphism through function overloading.
Practice exercise
Write a function doubleIt(int& n) that doubles n in place through the reference. Call it with x = 21, then print x.