Pointers and const
Rule:
β
const binds to left side; if none, binds to right.
1) Pointer to const (data const)
int a=10,b=20;
const int *p = &a;
- can change pointer β
- cannot change data through p β
p = &b; // β
*p = 5; // β
2) Const pointer (pointer const)
int * const p = &a;
- cannot change pointer β
- can change data β
*p = 5; // β
p = &b; // β
3) Const pointer to const data
const int * const p = &a;
Both cannot change.
Summary table
| Declaration | Change pointer? | Change data? |
|---|---|---|
const int *p |
β yes | β no |
int *const p |
β no | β yes |
const int *const p |
β no | β no |
Reading trick (right to left)
int * const pβ p is const pointer to intconst int * pβ p is pointer to const int