Const Locks the Pointer, Not the Memory
The Key Distinction
When you write:
int n = 108;
const int *ptr = &n;
You are making a promise about ptr — “I will not write through this pointer.” You are not making any promise about n itself. The memory where n lives is still writable through any other non-const access path.
Const Is an Access-Path Restriction
Think of const as a lock on a door, not a lock on the room. If you have two doors into the same room, you can lock one and leave the other unlocked.
int n = 42;
const int *readonly = &n; /* locked door */
int *readwrite = &n; /* unlocked door */
*readwrite = 99; /* OK — writing through the unlocked door */
*readonly = 99; /* COMPILER ERROR — door is locked */
Both pointers hold the same address. Both point to the same int. But one access path is restricted by the const qualifier, and the compiler enforces that restriction at compile time.
Where Is Const Enforced?
At compile time only. There is no runtime mechanism that marks memory as read-only. The compiler checks your code and refuses to compile if you try to write through a const-qualified pointer. Once the program compiles, the const qualifier has done its job — it doesn’t exist in the generated machine code.
This is different from, say, hardware memory protection or mmap with PROT_READ, which are actual runtime barriers.
Why This Matters
constis a contract between you and the compiler. Breaking it means a compile error, not a runtime crash.- A function taking
const int *pis saying “I will read*pbut not write to it.” This is documentation for humans and enforcement for the compiler, but the caller’s data is not protected from other code that might modify it. - Multiple pointers to the same memory can have different
constqualifiers. Each pointer has its own contract.
Key Takeaways
const int *prestricts this pointer, not the underlying memory.- The same memory can have both const and non-const pointers pointing at it.
constis a compile-time check. It does not survive into the runtime.- Multiple access paths to the same data can have different const qualifiers — each path is independent.