Difference between const int * and int * const
What you'll learn: How to distinguish between a pointer that cannot change the data it points to and a pointer that cannot change its own memory address.
The "Read-from-Right" Rule
In C, the const keyword can be slippery. To understand what is actually being protected, the best trick is to read the declaration backward (from right to left). This tells you exactly where the "lock" is applied.
1. const int *ptr (Pointer to a Constant)
Read it backward: ptr is a pointer to an integer that is constant.
Here, the data is locked. You can move the pointer to a different address, but you cannot use this pointer to change the value at that address.
- Analogy: You are a tourist with a camera. You can walk around to different statues (change the pointer), but you aren't allowed to paint or break the statues (change the data).
2. int * const ptr (Constant Pointer)
Read it backward: ptr is a constant pointer to an integer.
Here, the pointer itself is locked. The address stored in the pointer cannot change once it is initialized. However, you are free to modify the data living at that address.
- Analogy: You are a homeowner. You are legally tied to one specific house address (constant pointer), but you are allowed to renovate the interior or paint the walls however you like (modify the data).
Code Example
#include <stdio.h>
int main() {
int x = 10;
int y = 20;
// 1. Pointer to Constant
const int *ptr_to_const = &x;
ptr_to_const = &y; // ALLOWED: We can point somewhere else
// *ptr_to_const = 30; // ERROR: We cannot change the value via this pointer
// 2. Constant Pointer
int * const const_ptr = &x;
*const_ptr = 100; // ALLOWED: We can change the data
// const_ptr = &y; // ERROR: We cannot point to a new address
return 0;
}
Which one should you use?
Use const int * when passing a large array or structure to a function if you want to ensure the function doesn't accidentally modify your original data. Use int * const when you have a specific memory buffer (like a hardware register) that must never be swapped for another address during your program's execution.
Key takeaway
Read the declaration backward: const int * protects the value, while int * const protects the address.