In the following code, I’m expecting either the variable x
is put in a read-only memory and hence whatever we do on it via a non constant pointer/reference is without effect and in this case *y
should be equal to 0 or the keyword const
is just for compile time checking and we can do whatever we want at run-time and in this case both x
and *y
should be equal to 20. But what I’m getting is that x
is equal to 0 and *y
to 20 (it seems that y
is not pointing to x
!!)
#include <iostream>
int main()
{
const int x = 0 ;
int *y = (int*) &x ;
*y = 20 ;
std::cout << x << std::endl ; //output 0
std::cout << *y << std::endl ; //output 20
}