Consider the below code snippet:
int main()
{
const int i=3;
int *ptr;
ptr=const_cast<int*>(&i);
*ptr=5;
cout<<"i= "<<i<<endl; <------------------- statement 1
cout<<"*ptr= "<<*ptr<<endl; <------------- statement 2
return 0;
}
I am getting the output as:
i= 3
*ptr= 5
Why is the value of i is not changed through pointer?
I know casting away the const-ness of a variable which is explicitly declared as const and modifying its value is ‘Undefined Behavior’. I am curious to know: Is it any compiler optimization mechanism that ‘compiler replaces the variable in the program with the value’?.
It means the statement 1 is interpreted by the compiler as:
cout<<"i= "<<3<<endl;
Even if the statement
ptr=const_cast<int*>(&i);
is replaced by
ptr=(int*)(&i);
I am getting the same output: http://ideone.com/5lzJA
Yes; that will be why you don’t see the value changing. The behaviour of trying to modify a
constobject is left undefined in order to allow optimisations like that (as well as allowing the objects to be placed in unwritable memory).