I have the following code:
int main(){
const int a = 1;
const int* b(&a);
int* c = const_cast<int*>(b);
*c = 29;
cout<<*c<<a<<*b;
return EXIT_SUCCESS;
}
Why doesnt the value of 'a' change to 29? Does this mean that the constness of a is not removed when const_casting b?
Constant variables also allows the compiler certain optimizations, one of these is that the compiler can keep the value in the registers and not reload it. This improves performance but will not work with variables that changes since these need to be reread. Some compilers even optimize constants by not allocating a variable, but simply replacing the value inline. If you change the variable a to int
instead of const int
it will work, as it can be read in the documentation about the const_cast
operator from IBM:
If you cast away the constness of an object that has been explicitly declared as const, and attempt to modify it, the results are undefined.
You can find more information about the problem you are having and why it doesn't work here:
On a side note it can be noted that if you find yourself in need of using the const_cast
there is a good chance that you should reconsider your design instead.