1

I'm taking an entry level C++ course based on 'Thinking in C++. Forgive me for perhaps missing the obvious:

#include <iostream> // cout

using namespace std;

int main(){
    const int i = 0;
    int* j;
    j = const_cast<int*>(&i);
    *j = 5;
    cout << (&i) << "," << i << "," << j << "," << (*j) << endl;
    system("pause");
}

My system returns:

'0x22ff74,0,0x22ff74,5'

I only declared two variables, one containing an int and one containing a pointer to that same int. I thought const_cast was to 'convert from a const to a nonconst'. So how is cout finding three distinct values?

GregT
  • 1,300
  • 3
  • 16
  • 25
  • 1
    Because undefined behavior. – user703016 May 23 '14 at 17:49
  • 1
    Also, I'm not sure why you say "three" distinct values, I only see two. – Mooing Duck May 23 '14 at 17:49
  • Your compiler is free to treat `const int i = 0` similar to something like `#define i 0` and just blindly substitute 0 for `i`, without regard to whether you went behind its back and changed the value of the variable. But it's not required to, either. So if you try this on a different platform, you may get a different answer. That's perfectly valid undefined behavior... – twalberg May 23 '14 at 17:57
  • @Mooing Duck, I meant the 2 values plus the address. THANKS A LOT for these comments, it is not clear at all from the book that changing const_cast is asking for such trouble. But it is from the spec and these responses. Cheers. – GregT May 23 '14 at 18:06

0 Answers0