Q:

C++ const pointers - Unexplained behaviour

I have this piece of code:
const int x = 7;
const int &y = x;

int *z = (int*)&y;
*z = 8;

cout << x<< endl;
cout << y<< endl;
cout << *z<< endl;

Which produces the following output:
7
8
8

I know that one should not remove the const as I did above. However, why does x print out 7? I've only created a single var, so if the output shows 7 and 8, then then there should be 2 vars created. How come there be 2 different numbers printed.

A:

I know that one should not remove the const as I did above. 

Right.  Doing so is undefined behaviour, which means anything can happen.  (More precisely, creating z is not undefined behaviour; modifying x through it is.)

However, why does x print out 7? I've only created a single var, so if the output shows 7 and 8, then then there should be 2 vars created. How come there be 2 different numbers printed.

Reasoning about undefined behaviour is weird - but it can be useful to understand what is happening for debugging purposes.  It this case, what has almost certainly happened, is that the compiler has optimized:
cout << x<< endl;

to
cout << 7 << endl;

because there is no way you can legitimately modify the value of x.  You then illegitimately modify the value of x, and manage to print out the new value.
Important Note
Do not attempt to rely on this behaviour; as I said above, it is only useful for debugging purposes.  If the compiler changes it might get better at optimization and just print 7 for all values (because *z = 8 is undefined behaviour), or it might put x in read-only memory (and cause a access violation), or it might end up printing 8 for all values, or anything else might happen.

A:

However, why does x print out 7?

Modifying a const object has undefined behaviour.

