Top-level const vs Low-level const
- Top-level
const
: the object itself is const; if it is a pointer, the pointer itself is const. E.g.int *const ptr
. - Low-level
const
: the object being pointed or referenced is const. E.g.const int *ptr
.
const int * const
has both top-level const and low-level const.
For example, for a non-pointer variable
// x is a top-level const integer
const int x = 10;
// Error: Cannot modify a const variable
x = 20;
For a pointer, top-level const:
// ptr is a top-level const pointer
int *const ptr = &x;
// OK: Modifies the value pointed to by ptr
*ptr = 20;
// Error: Cannot change the address stored in ptr
ptr = &y;
A pointer, low-level const:
// ptr is a low-level const pointer
const int *ptr = &x;
// Error: Cannot modify the value pointed to by ptr
*ptr = 20;
// OK: Can change the address stored in ptr
ptr = &y;