When to use const with pointers
What you'll learn: How to protect your data or your address by strategically placing the const keyword in pointer declarations.
The "Briefcase" Analogy
Think of a pointer like a courier holding a briefcase. The pointer is the person (the address), and the data is what's inside the briefcase (the value). In C, you use const to decide if you want to lock the briefcase, tie the briefcase to the courier's hand, or both.
Three ways to use const
Depending on where you place the keyword, you change what is "read-only."
-
Pointer to Constant Data (
const int *ptr) Here, the briefcase is locked. You can tell the courier to go to a different house (change the address), but you cannot change what is inside the briefcase. This is the most common use, especially when passing strings or arrays to functions where you want to ensure the function doesn't accidentally modify the original data. -
Constant Pointer (
int * const ptr) Here, the briefcase is handcuffed to the courier. You can change the contents of the briefcase as much as you like, but the courier is stuck at one specific house forever. They cannot point to a new memory address. -
Constant Pointer to Constant Data (
const int * const ptr) The briefcase is locked and handcuffed. Nothing can change.
Seeing it in code
Here is how these variations look in action:
#include <stdio.h>
int main() {
int gold = 100;
int silver = 50;
// 1. You can't change the value, but you can change the address
const int *price = &gold;
// *price = 200; // ERROR: Data is protected
price = &silver; // ALLOWED: Pointer can move
// 2. You can change the value, but you can't change the address
int * const vault = &gold;
*vault = 200; // ALLOWED: Data can change
// vault = &silver; // ERROR: Pointer is locked
return 0;
}
Why does this matter?
Using const isn't just about preventing errors; it's about intent. When you write a function like printString(const char *s), you are promising other programmers (and yourself) that the function will only read the string, not destroy it. This makes your code safer and much easier to debug.
Key takeaway
Place const before the * to protect the data, and after the * to protect the address.