Consider the below code snippet:
int main()
{
const int i=3;
int *ptr;
ptr=const_cast(&i);
*ptr=5;
cout<<\"i= \"<&
It's not an optimization. An optimization is the transformation of a program into another program that has the same behaviour, but uses less resources. Your program does not have any defined behaviour, so you can't possibly apply any transformation to it that yields the same behaviour.
I hade same problem, I added volatile, now it's modifying:
#include<iostream>
using namespace std;
int main()
{
volatile const int a=5;
int *p = const_cast<int*>(&a);
*p=6;
cout<<"a="<<a;
return 0;
}
Output:
a=6
volatile tells compiler that the identifier can be modified (if not by this code then by some one else, so do not perform any optimization)
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).
Most likely since it is a const int, the compiler is optimizing and directly replacing it with the value of i.
i
could be stored in a protected area of memory for ptr
to point to. Of course anything can be the case, which is why it's undefined - which basically means don't depend on any particular behaviour occurring if you do try to trigger undefined behaviour.
For all you know it could cause your computer to go into cardiac arrest or start shooting out laser beams, but you never know because it's ... (w a i t _ f o r _ i t) ... undefined ;).