Wierd Behaviour

1
2
3
4
5
6
7
8
9
10
int main()
{
const int i = 42;

*(int*)&i = 43;       // What is happening here

printf ("i %d,%d,%d",i,*(&i),*(int*)&i); // Why the result is 42 42 and 43

return 0;
}


please see the comments. why the result is 42 42 43
The result can be as well 3 14 43549059.
This is not valid C++ code. You are breaking the type system here.
Last edited on
Please let me know whats wrong in the code....i am trying to find it out but un able to.
the problem is that you're removing const. If you're writing this 'i' or '*(&i)' the compiler knows that it's the constant 42 and replace the expressing accordingly. When you cast away the const it uses the variable which is set to 43 previously.
Topic archived. No new replies allowed.