char s[] = "Hello";
const char* pc = s; // pointer to constant
pc[3] = 'g'; // error
My C++ book I'm reading says this is an error, because pc points to constant.
Does that mean constant variables can't change value? Therefore, by trying to assign pc[3] to 'g' we are trying to change the value of a constant variable which is illegal? Does that mean s is constant? What if the last line of code had been:
I don't want to split hairs, but the statement I was troubled by was:
const pointer means you cannot change what the pointer points to
This statement is true, but we we are not talking about a const pointer. If pc were a const pointer then it would be true that you could not change what the pointer points to and the following statement would be wrong:
pc = &someOtherCharVariable; // error pc is a const pointer
WHAT pc ACTUALLY IS
pc is a pointer to a char variable with the restriction that it can't change the char variable it is pointing to.
Well I suppose it depends on your personal terminology.
"const pointer" vs. "pointer const"
When I say "const pointer" I refer to a non-const variable which is a pointer to a const variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int a, b;
//----------------
constint* cp = &a; // the pointer itself is not const, what it points to is const
*cp = 0; // error
cp = &b; // ok
//-----------------
int* const pc = &a; // the pointer itself is const, what it points to isn't
*pc = 0; // ok
pc = &b; // error