I am learning pointers and got confused when I tried to modify the value of a const int through its address. I am not sure if it has any practical meaning. I just want to learn how the pointer works for const int. Here is the code:
const int a = 10;
*((int*)&a) = 20;
cout << a << endl;
cout << *(&a) << endl;
It prints 10 and 20. But I thought it should print 20 and 20, because in the second line, I casted &a and modified its value. So the value of a should change, because the bit pattern at that address changed.
I also tried the following code:
int a = 10;
*((int*)&a) = 20;
cout << a << endl;
cout << *(&a) << endl;
It prints 20 and 20 as I expected. I just don't understand how does const works in this case. I really appreciate it if anyone could give any suggestions.