why is it possible to change the value of the constant z in the C++ snippet below? What is the meaning of (int&) in the 5th line? Note that the addresses of x, y, z are different (cout << &x << &y << &z). Thank you very much!
int x = 2;
int y = 3;
const int z = x;
cout << z; // the result is 2
(int&) z = y;
cout << z; // the result is 3
Because in this case we have a cast on the left side of an assignment expression that tells to compiler we are forcing our identifier in order it behaves as a not read-only reference to its memory location, and since we are knowingly "forcing" a behaviour, compiler trust us and allows this assignment.
In some cases this is potentially dangerous, as when you assign the const identifier with a literal value, because it is not standard how compilers implement this initialization, in fact some compilers seems that replace the occurrences of identifiers with the literal values, as well as a macro expansion, so you have to pay a very close attention doing this operation.