Two different values at the same memory address

Why are there two different datas at the same address?

There aren't. The compiler is allowed to optimize any mention of a const to be as though you had written its compile-time value in there.

Note that the compiler is also allowed to generate code that erases your hard disk when you run it if you do nasty tricks like writing to memory reserved for consts.


You get undefined behavior on the line *pN = 33;, because you're modifying a const value. Anything can happen. Don't do it.


Likely, though, your compiler simply optimized. In the line:

cout << N << '\t' << &N << endl;

It knows N is a constant expression with the value 22, so just changes the line to:

cout << 22 << '\t' << &N << endl;

And on your next line, you fetch the value at the address of N, which you "set" to 33. (But really, all you did was remove any guarantees about the state of your program.)

Tags:

C++