Pointers themselves can be declared const
just like
other objects. In these cases, the pointer can't be made
to point elsewhere, but does not prevent modification of
what it points. Careful positioning of the keyword
const
is
required to distinguish constant pointers from pointers
to constants:
int array = { 1, 2, 4, 5 }; int *ip = array; /* a pointer to an integer */ int *const ipc = array; /* a constant pointer to an integer */ const int *const icpc = array; /* a constant pointer to a constant integer */ ipc[0] = ipc[1] + ipc[2]; /* okay */ ip += 2; /* okay */ ipc += 1; /* wrong; pointer is constant */ icpc[1] += 4; /* wrong; pointed-to object is constant */
This example shows a modifiable array whose members are being accessed through four pointers with slightly different types.