-1

Someone showed me the following code snippet and asked what it should output

#include <iostream>
using namespace std;

int main() {
    const int value = 10;
    int* p = (int*)&value;
    *p = 20;

    cout << value << " " << *p << endl
        << &value << " " << p << endl;

    return 0;
}

As you can see, there's a constant value which is 10, and there's a pointer p which points to the address of value, then the address pointed gets a different value.

I expected the program to print 20 20 but it actually prints 10 20.
It also shows that the two valuables have the same address. Can someone explain what's going on behind the scenes here?

qwertymk
  • 34,200
  • 28
  • 121
  • 184
  • 5
    Undefined behavior...? –  Dec 07 '14 at 03:45
  • @remyabel maybe but what happened? – qwertymk Dec 07 '14 at 03:45
  • See [How is a variable at the same address producing 2 different values?](http://stackoverflow.com/q/22656734/1708801) ... attempting to modify a const object is undefined behavior this question is likely a duplicate. – Shafik Yaghmour Dec 07 '14 at 03:46
  • @Shafik Not sure what question n.m. marked as a duplicate, but the one you linked seems like a fair duplicate. Is it really necessary to let the answerers gain rep for essentially repeating the same information? –  Dec 07 '14 at 04:03
  • @remyabel yes but I answered the question so I won't close it, there may be better duplicate but I don't have the time to look. See this [meta question](http://meta.stackoverflow.com/q/277126/1708801). – Shafik Yaghmour Dec 07 '14 at 04:04
  • So you managed to break c++...nice – smac89 Dec 07 '14 at 04:05

1 Answers1

3

Undefined behavior and an optimizing compiler. The compiler knows from value's declaration that value's value will never change in a well-formed program, so it optimizes out the bits where value's value would be checked and just takes the value it knows value has.

As for the addresses, you never take the address of p, and that p is the same as &value is not surprising because you assigned it that way a few lines earlier.

Wintermute
  • 42,983
  • 5
  • 77
  • 80