⏱ 1 min read

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 int
  • const int * p β†’ p is pointer to const int