Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it doesn't change const object in my code? [duplicate]

Tags:

c++

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 ?

like image 471
David Mnatsakanyan Avatar asked Feb 23 '26 23:02

David Mnatsakanyan


1 Answers

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.)

like image 116
ruakh Avatar answered Feb 26 '26 13:02

ruakh