What is the difference between a const pointer and a pointer to const?
Last updated
A pointer to const protects the pointed-to data (you can't change the value through it, but you can repoint it); a const pointer fixes the pointer itself (it always points at the same address, but you may modify the value). Read the declaration right-to-left.
Pointer to const:
const int* p:*p = 5;is illegal;p = &other;is legal.Same as
int const* p.
Const pointer:
int* const p:*p = 5;is legal;p = &other;is illegal (must be initialized at declaration).Const pointer to const:
const int* const p: Neither the value nor the pointer can change.
[lang:cpp]
int a = 1, b = 2;
const int* p1 = &a; // can't change *p1, can change p1
p1 = &b; // ok
int* const p2 = &a; // can change *p2, can't change p2
*p2 = 9; // ok