3

Here is the code

int main()
{   
  const int i = 2;
  const int * pi = &i;
  int* j = const_cast<int *> (pi);
  *j = 11;
  std::cout << *pi << std::endl;
  std::cout << i << std::endl;
  return 0;
}

result:

11

2 <--- why ?

David Mnatsakanyan
  • 455
  • 1
  • 4
  • 15
  • right of the bat i would guess is that a pointer is always mutable because you know, its direct access to the memory channel and then can always be edited. Const is nothing more than agreeing that you won't change that. but if you put it in a pointer the memory address can always be overwritten because RAM doesn't recognise const. But, this is all a guess, i am curious to other people's answers. I'm not that versed in pointer behaviour. – Tschallacka Feb 24 '15 at 07:15

1 Answers1

9

As http://en.cppreference.com/w/cpp/language/const_cast puts it:

Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior.

In this case, your compiler has apparently optimized

  std::cout << i << std::endl;

to

  std::cout << 2 << std::endl;

since i is const, and its value cannot change in any valid program. (As it happens, the value of i did change, because the program is invalid; but your compiler — quite rightly — did not concern itself with that possibility. C++ compilers, and programmers, generally consider it more important to optimize correct code than to mitigate the incorrectness of incorrect code.)

ruakh
  • 175,680
  • 26
  • 273
  • 307