0

friends.

Recently I experimented a bit a C++ constants.

The code is:

#include <iostream>

int main() {
    const int c = 1;
    const int* ptr = &c;
    int* tmp = const_cast<int*>(ptr);
    *tmp = 5;
    std::cout << &c << " " << ptr << " " << tmp << "\n"; 
    std::cout << c << " " << *ptr << " " << *tmp;
}

I have investigated assembly code at godbolt: https://godbolt.org/z/7e3o7bWrs

The assembly code seems like doing what I wrote, exactly moving address of c into tmp variable and changes variable at this address.

Can you please tell me, why there is could be two different values at the same addresses?

Thank you.

Mr.Donaldo
  • 15
  • 3
  • 2
    TL;DR - it's Undefined Behaviour. It seems that line 39 in your assembly is the key, it moves `1` as literal to the register and calls `std::ostream::operator<<(int)` in line 41 - the compiler optimized `c` away, because it knows its value can never change, and replaced it with just `1` directly. – Yksisarvinen Sep 11 '22 at 21:35
  • 1
    `any attempt to modify a const object during its lifetime results in undefined behavior.`, you are not experimenting on c++, you are experimenting on the compiler. – Ahmed AEK Sep 11 '22 at 21:39
  • 2
    To be clear - there are not "two different values at the same address". Your program has Undefined Behavior and therefore you can not make any valuable observations about the program's behavior. – Drew Dormann Sep 11 '22 at 21:51

0 Answers0