0
int main()
{
    const int  i = 9;
    const int* p = &i;

    int *c = const_cast<int*>(p);
    *c = 3;
    cout<<"i = "<<i<<endl;
    cout<<"p = "<<p<<endl;
    cout<<"*p = "<<*p<<endl;
    cout<<"c = "<<c<<endl;
    cout<<"*c = "<<*c<<endl;
    cout<<"&i = "<<&i<<endl;


    return 0;
}

Hello all, the previously stated code has an output that doesn't make any sense to me, the output looks like the following C++ code output. My question is, how can you have I have 2 different values in the same memory address? Is it possible? Is there any other case that this might happen in C++? and Can the opposite happen such that compiler moves a value from a specific place in memory and assign it to different place?

Tarek
  • 31
  • 1
  • 4
  • 4
    *Undefined behavior* is undefined – UnholySheep Jul 31 '17 at 11:13
  • 1
    You have UB with `*c = 3;` – Jarod42 Jul 31 '17 at 11:13
  • 1
    You lied to the compiler (`const_cast`) and it believed you. Lying can have unintended consequences. – molbdnilo Jul 31 '17 at 11:20
  • This is a very interesting question. Since you declared `i` as `const int`, the compiler assumed that `i` was not going to change and inlined the value in the `cout` statement. But no, there aren't two different values in the same address. – tuket Jul 31 '17 at 11:39

0 Answers0