Memory & Pointers

const-correctness with pointers

With a plain pointer there are two different things you might want to lock down: the value it points at, and where it points. The const keyword lets you forbid changes to either one — and the placement of const decides which. Getting this right is what people mean by const-correctness, and it is mostly about reading the declaration carefully.

Read it from the variable name outward. A pointer to const, written const int *p, means 'p may move, but you may not write through it' — *p = 5 is rejected, while p = &other is fine; the pointee is read-only via this pointer. A const pointer, written int *const p, is the reverse: 'p is fixed, but the value it names may change' — p = &other is rejected, while *p = 5 is fine. And const int *const p locks both. A helpful rule of thumb: whatever const sits immediately to the left of cannot change — left of the star protects the pointee, right of the star protects the pointer. A pointer to const is the everyday workhorse: a function that promises not to modify its input takes a const char *, like strlen(const char *s).

const-correctness is not a runtime guarantee enforced by hardware; it is a compile-time promise the compiler checks and a piece of documentation in the type. It catches accidental writes, lets callers pass read-only data safely, and communicates intent. The honest caveat: you can cast const away, and writing through a pointer obtained that way to an object that was truly const is undefined behaviour — const is a contract you should keep, not a lock you cannot pick.

const int *a; allows a = &y but rejects *a = 1 (pointee is read-only). int *const b = &x; allows *b = 1 but rejects b = &y (pointer is fixed). Reading right-to-left: 'a is a pointer to const int'; 'b is a const pointer to int'.

Left of the star locks the pointee; right of the star locks the pointer.

const on a pointer is checked at compile time, not enforced by memory protection — and it can be cast away. Doing so to write a genuinely const object is undefined behaviour. Treat const as an honest promise about intent, and prefer const char * for inputs you do not modify.

Also called
pointer to const vs const pointerconst 正確性