Constant pointer to a constant
What you'll learn: How to create a pointer that is completely locked down, preventing you from changing both the address it holds and the data it points to.
The Ultimate Lockdown
In previous lessons, we saw that const can be used to protect either the "value" at an address or the "address" itself. But what if you want a pointer that is strictly read-only and cannot be moved?
This is a constant pointer to a constant. Think of it like a fixed security camera bolted to a wall. You cannot move the camera to a different wall (the pointer address is constant), and you cannot reach through the lens to change the scene it is looking at (the data is constant). It is the most restrictive way to handle a pointer in C.
The Syntax
To achieve this, you place the const keyword in two places: before the data type and after the asterisk.
#include <stdio.h>
int main() {
int high_score = 100;
int new_score = 200;
// A constant pointer to a constant integer
const int * const ptr = &high_score;
printf("Current score: %d\n", *ptr);
// ERROR: You cannot change the value being pointed to
// *ptr = 150;
// ERROR: You cannot change the address the pointer holds
// ptr = &new_score;
return 0;
}
Why use this?
You might wonder why we would ever want to be so restrictive. This is primarily a safety feature for complex systems. When you pass a pointer to a function and declare it as a constant pointer to a constant, you are making a "contract." You are telling the compiler (and other programmers) that this function will not touch the data and will not accidentally point somewhere else during its execution.
By using two const keywords, you eliminate the risk of accidental side effects. It makes your code "immutable," meaning once that pointer is initialized, it is set in stone for its entire lifetime.
Key takeaway
A const type * const name declaration creates a dual-layer lock, ensuring neither the data nor the pointer's destination can ever be modified.