Loading lessons...
Pointers and Const
const and pointers combine in three ways. The only question that matters: which part is const - the pointer, or the thing it points to?
Pointer to const
Code
cpp
int value = 5;
const int* ptr = &value; // pointer to a const int
*ptr = 10; // error: the value is read-only (can't change through ptr)
cout << *ptr; // fine: reading is allowed
const int* reads "pointer to a const int". The pointed-to value is const, but the pointer itself can be moved to another int.
Const pointer
Code
cpp
int* const ptr = &value; // a const pointer
ptr = &other; // error: the pointed int can still change
*ptr = 10; // fine: the int value is not const
int* const reads "a const pointer to int". This time the pointer is locked in place, but the value it points to is mutable.
Const pointer to const
Code
cpp
const int* const ptr = &value; // both const
Neither the pointer nor the value can change through it.
Which const does what
- The const before the type (
const int*) protects the pointed value. - The const after the star (
int* const) protects the pointer.
Code
cpp
const int* // pointer to const int -> value const
int* const // const pointer to int -> pointer const
const int* const // const pointer to const int -> both
TL;DR
const int*- the pointed value is const.int* const- the pointer is const.const int* const- both are const.- The position of the const tells you which part it protects.