Constant pointer to a value (int * const p)
What you'll learn: How to lock a pointer so it stays glued to one specific memory address forever.
The Loyal Butler
Imagine a pointer is like a professional butler. Usually, a butler is a freelancer; today he works for Mr. Smith, but tomorrow he might quit and go work for Mrs. Jones. In C, we "reassign" a pointer by pointing it to a new address.
However, a constant pointer is like a butler who has signed a lifetime contract with one specific house. He is legally bound to that address. He can still go inside the house and change the furniture (change the value), but he can never, ever leave to work at a different house.
The Syntax: int * const p
In C, the position of the const keyword is vital. When const comes after the asterisk (*), it modifies the pointer variable itself.
int gold_mine = 500;
int silver_mine = 200;
// The 'const' is after the '*', so the address is locked.
int * const p = &gold_mine;
*p = 600; // LEGAL: We can change the value at the address.
p = &silver_mine; // ERROR: We cannot point to a new address.
Why use this?
You use a constant pointer when you want to protect the "where," but not necessarily the "what."
For example, if you are writing code for a computer’s hardware where a specific memory address controls the screen, you never want your pointer to accidentally drift away to a different part of memory. If it did, your program might crash or start overwriting important data. By using int * const, you tell the compiler: "If I ever try to make this pointer look anywhere else, stop me immediately with an error."
Read it Backward
A great trick for C pointers is to read the declaration from right to left:
int * const p
- "p is a constant pointer to an int."
The "constant" part hits the pointer first, locking the address. Because the int part isn't marked constant, the data inside remains fair game for modification.
Key takeaway
A constant pointer (* const) is a fixed arrow: it can change the data it points to, but it can never be reassigned to point to a different memory location.