Reputation: 22821
#include <iostream>
int main()
{
const int i=10;
int *p =(int *) &i;
*p = 5;
cout<<&i<<" "<<p<<"\n";
cout<<i<<" "<<*p;
return 0;
}
Output:
0x22ff44 0x22ff44
10 5
Please Explain.
Upvotes: 1
Views: 181
Reputation: 153909
You've attempted to modify a const object, so the behavior is undefined. The compiler has the right to suppose that the const object's value doesn't change, which probably explains the symptoms you see. The compiler also has the right to put the const object in read only memory. It generally won't do so for a variable with auto lifetime, but a lot will if the const has static lifetime; in that case, the program will crash (on most systems).
Upvotes: 5
Reputation: 10142
Well, your code obviously contains undefined behaviour, so anything can happen.
In this case, I believe what happens is this:
In C++, const ints are considered to be compile-time constants. In your example, the compiler basically replaces your "i" with number 10.
Upvotes: 12
Reputation: 1302
I'll take a shot at it: since there's no logical reason for that output, the compiler must have optimised that wretched cout<<i<<" "
to a simple "cout<<"10 "
. But it's just a hunch.
Upvotes: 2