There is a difference between a constant of type char
being pointed to (a.k.a. the pointee) and a constant pointer of type char*
. If you want to protect a pointer from (accidental) modification, you can declare it constant:
char* p = '...';
char* const cp = 'Hello, World!'; // a constant pointer
cp[1] = ','; // okay, the pointee is not constant
cp = p; // error, the pointer is constant
A variable pointer to a constant can change:
char *p = '...';
const char* pc = 'Hello, World!'; // pointer to a constant
pc[1] = ','; // error, the pointee is constant
pc = p; // okay
And finally, you can declare a constant pointer to a constant with
const char* const cpc = 'Hello, World!';
cpc[1] = 'a'; // error, pointee cannot change
cpc = p; // error, pointer cannot change
This is from §5.4.1 of “The C++ Programming Language”, Stroustrup.
You can change A
to 'B'
in the last line, because A
is of type char
and therefore can be changed. It isn’t declared a const char
, which would prevent you from doing so.