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 ?
The statement int* c = const_cast<int>(b) returns a pointer c that refers to a without the const qualification of a . This process of using const_cast to remove the const qualification of an object is called casting away constness. Consequently the compiler does allow the function call f(c) .
No! You shouldn't modify a const variable. The whole point of having a const variable is to be not able to modify it. If you want a variable which you should be able to modify, simply don't add a const qualifier on it.
In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization. In this section we will see how to change the value of some constant variables. If we want to change the value of constant variable, it will generate compile time error.
Changing Value of a const variable through pointerThe compiler will give warning while typecasting and will discard the const qualifier. Compiler optimization is different for variables and pointers.
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
char
s.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With