I have this code
int main()
{
char A = 'E';
const char * i;
i = &A;
A = 'B';
}
which actually compiles with MSVC, why?
Isn’t a const char * supposed to point to a constant character variable? Why can I change A to ‘B’ in the last line?
Am I missing something?
There is a difference between a constant of type
charbeing pointed to (a.k.a. the pointee) and a constant pointer of typechar*. If you want to protect a pointer from (accidental) modification, you can declare it constant:A variable pointer to a constant can change:
And finally, you can declare a constant pointer to a constant with
This is from §5.4.1 of “The C++ Programming Language”, Stroustrup.
You can change
Ato'B'in the last line, becauseAis of typecharand therefore can be changed. It isn’t declared aconst char, which would prevent you from doing so.