Consider the below code snippet:
int main()
{
const int i=3;
int *ptr;
ptr=const_cast(&i);
*ptr=5;
cout<<\"i= \"<&
Is it any compiler optimization mechanism that compiler replaces the variable in the program with the value?
Yes; that will be why you don't see the value changing. The behaviour of trying to modify a const
object is left undefined in order to allow optimisations like that (as well as allowing the objects to be placed in unwritable memory).