It is certainly undefined behavior, but I am strong proponent of understanding symptoms of undefined behavior for the benefit of spotting one. The results observed can be explained in following manner:
const int a = 5
defined integer constant. Compiler now assumes that value will never be modified for the duration of the whole function, so when it sees
cout<<&a<<" = "<<a;
it doesn’t generate the code to reload the current value of a
, instead it just uses the number it was initialized with – it is much faster, than loading from memory.
This is a very common optimization technique – when a certain condition can only happen when the program exhibits undefined behavior, optimizers assume that condition never happens.
solved Change constant value [duplicate]