Home

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

Key Takeaways

  1. const int *p restricts this pointer, not the underlying memory.
  2. The same memory can have both const and non-const pointers pointing at it.
  3. const is a compile-time check. It does not survive into the runtime.
  4. Multiple access paths to the same data can have different const qualifiers — each path is independent.
Tags: CPointers