Remove const-ness from a variable

David Faizulaev picture David Faizulaev · Mar 12, 2013 · Viewed 12.8k times · Source

i'm trying to remove const-ness from a variable (char*), but for some reason when i try to change the value, the original value of the const variable still remains the same.

 const char* str1 = "david";
 char* str2 = const_cast<char *> (str1);
 str2 = "tna";

now the value of str2 changes but the original value of str1 remains the same, i've looked it up on Google but couldn't find a clear answer.

when using const_cast and changing the value, should the original of the const variable change as well ?

Answer

Joseph Mansfield picture Joseph Mansfield · Mar 12, 2013

The type of str1 is const char*. It is the char that is const, not the pointer. That is, it's a pointer to const char. That means you can't do this:

str1[0] = 't';

That would change the value of one of the const chars.

Now, what you're doing when you do str2 = "tna"; is changing the value of the pointer. That's fine. You're just changing str2 to point at a different string literal. Now str1 and str2 are pointing to different strings.

With your non-const pointer str2, you could do str2[0] = 't'; - however, you'd have undefined behaviour. You can't modify something that was originally declared const. In particular, string literals are stored in read only memory and attempting to modify them will bring you terrible misfortune.

If you want to take a string literal and modify it safely, initialise an array with it:

char str1[] = "david";

This will copy the characters from the string literal over to the char array. Then you can modify them to your liking.