The const
keyword means “read-only” – you can't modify the object it applies to. But when combined with pointers, it depends where you put `const.
Always read const
right before the thing it qualifies.
Let's explore the variations:
1️⃣ const
Data – Pointer to Constant
const int *ptr;
// or
int const *ptr;
✅ You can change ptr
to point elsewhere.
❌ You cannot change the value pointed to.
Meaning: “Pointer to a constant int”
int x = 5, y = 10;
const int *ptr = &x;
*ptr = 6; // ❌ Error: read-only value
ptr = &y; // ✅ Okay: pointer can change
2️⃣ Constant Pointer – const
Pointer to Data
int *const ptr = &x;
✅ You can change the value being pointed to.
❌ You cannot change where the pointer points.
Meaning: “Constant pointer to an int”
int x = 5, y = 10;
int *const ptr = &x;
*ptr = 7; // ✅ Okay: value can change
ptr = &y; // ❌ Error: pointer is constant
3️⃣ Constant Pointer to Constant Data
const int *const ptr = &x;
❌ You cannot change the value.
❌ You cannot change the pointer.
Meaning: “Constant pointer to constant int”
int x = 5, y = 10;
const int *const ptr = &x;
*ptr = 7; // ❌ Error
ptr = &y; // ❌ Error
Visual Summary
Declaration | Read As | Can Modify Value? | Can Reassign Pointer? |
---|---|---|---|
int *ptr | Pointer to int | ✅ Yes | ✅ Yes |
const int *ptr | Pointer to const int | ❌ No | ✅ Yes |
int *const ptr | Const pointer to int | ✅ Yes | ❌ No |
const int *const ptr | Const pointer to const int | ❌ No | ❌ No |
Const in Function Parameters
These declarations are functionally different:
void foo(const int* p); // Won't modify *p
void foo(int* const p); // Won't reassign p, but can modify *p
void foo(const int* const p); // Won’t do either