Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove const-ness from a variable

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 ?

like image 526
David Faizulaev Avatar asked Mar 12 '13 10:03

David Faizulaev


People also ask

How do I remove a const?

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) .

Can I change const to VAR?

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.

Can you modify const in C?

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.

What happens if you try to change a const?

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.


1 Answers

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.

like image 107
Joseph Mansfield Avatar answered Dec 01 '22 01:12

Joseph Mansfield