2

I am just playing around to see where my current understanding of C++ behaviour ends. I wrote the following code, and got some very unexpected results.

#include <iostream>
#include <cstddef>
using namespace std;

int main()
{
    const char c = 'A';
    cout << c << endl;
    size_t l = (size_t)(&c);
    char* d = (char*)l;
    *d = 'B';
    cout << (size_t)d << " " << (size_t)&c << endl;
    cout << *d << " " << c << endl;
}

The first line outputs 'A', as expected. On the second line, the two addresses are the same. However, the third line outputs "B A".

Obviously this is terrible code, but why didn't the value of c change (or why didn't it fail to compile?) In other words, if they both have the same address, why don't they have the same value?

My system is GCC 4.8.1 64-bit on MS Windows 7, x86, if it matters.

Michael Stachowsky
  • 717
  • 1
  • 5
  • 21
  • 6
    This is called [*Undefined Behaviour*](http://stackoverflow.com/a/4105123/1171191). If you deliberately break the rules, anything can happen, in this case probably due to the compiler optimizing away the access to a `const` value, assuming it can't change. But I do mean **anything** can happen. It might crash, it might give strange results, it might only crash or give strange results occasionally, and worst of all, **it might appear to work perfectly** (then break horribly at some point in the future). – BoBTFish Mar 09 '17 at 11:26
  • I see. So it's "we didn't specify it, but *something* is going to happen, so don't do it" and that's it? – Michael Stachowsky Mar 09 '17 at 11:28
  • 2
    Pretty much. Undefined Behaviour exists in The Standard (mainly) for things that would be expensive, or impossible, for the compiler to check, or to allow optimizations. – BoBTFish Mar 09 '17 at 11:29
  • makes sense. Thanks. – Michael Stachowsky Mar 09 '17 at 11:30

0 Answers0