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:
Does that mean constant variables can't change value?
No they can't - otherwise they wouldn't be 'constant'. But C++ being C++ you can change a constant
using a special cast - see example further down.
Therefore, by trying to assign pc[3] to 'g' we are trying to change the value of a constant variable which is illegal?
Yes
Does that mean s is constant ? s is the name of an array variable. You can assign it's value to a char* as you did constchar* pc = s; but you cannot change s
What if the last line of code had been:
char s[] = "Hello";
s[3] = 'g';
OK
Special Note: - Changing const objects
C++ does allow you to change const objects - which may seems a strange thing to allow - using the const cast
1 2 3
constchar s[] = "Hello";
s[3] = 'x'; //Error - attempting to chang const object
static_cast<char>(s[3]) = 'x'; //OK - You can cast away constantness temporarily.
Thank you so much! I did some research on my own as well and I have come to the same conclusion. However, I would like to clarify. s is mutable, but you can't use pc to mutate it. Therefore, the statement:
"Therefore, by trying to assign pc[3] to 'g' we are trying to change the value of a constant variable which is illegal"
is misleading. pc[3] is a location in memory. By making pc a "pointer to a char constant" all we are doing is giving pc a restriction. The restriction is, "you can't use pc to change the value of the char it is pointing to." However, that doesn't necessarily mean that the address in memory that pc is pointing to is constant.
Cheers Dunson
p.s. I found that other bit of knowledge helpful too. The fact that you can change a const object using the const cast.