const pointer in C: solved exercise
const pointer in C: solved exercise
If you searched for a solved const pointer in C, here are the three combinations of const with pointers, with examples showing what is allowed and what the compiler rejects.
The rule is to read the declaration right to left: the const closest to the variable name freezes the pointer itself; the const closest to the base type freezes the pointed-to value.
Problem statement
Declare and use the three variants:
const int *p— pointer to constant integer (cannot modify the value).int * const p— constant pointer to integer (cannot change where it points).const int * const p— constant pointer to constant integer.
Show which operations are valid and which are invalid for each one.
C solution
Expected output
Common mistakes
- Confusing what is constant:
const int *pfreezes the value, not the pointer;int * const pfreezes the pointer, not the value. - Assigning a
constpointer to a non-const pointer without a cast:int *q = p1;triggers a compiler warning because theconstprotection is lost. - Trying to modify the value through a
const int *by casting awayconst: this is undefined behavior if the original object was declaredconst. - Not initializing an
int * constat declaration: a constant pointer must be initialized where it is declared (it cannot be reassigned later).
Practical use
const int * is used in function parameters to guarantee that the original data is not modified (strcmp, strlen, printf all use const char *). int * const appears in embedded hardware registers where the address is fixed but the value is writable. const int * const expresses a fully immutable pointer, useful for read-only configuration tables.
Recommended next exercise
- Dynamic buffer in C: solved exercise
- Pointer to struct in C: solved exercise
- Arrays as parameters in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Why does the compiler warn when assigning const int * to int *?
Because losing the const opens the possibility of modifying data the programmer marked as immutable. The compiler issues a warning (or error in strict mode) to signal that protection is being silently dropped.
What does const mean in the const char *s parameter of printf?
It means that printf commits to not modifying the string pointed to by s. It is a guarantee to the caller: you can safely pass a string literal (which lives in read-only memory) without risk of printf modifying it.
How do you read const int * const *pp?
Right to left: pp is a non-constant pointer (*pp) pointing to a constant pointer (* const) to a constant integer (const int). In practice, double indirection is rare but appears in tables of pointers to read-only strings such as const char * const argv[].