0

In the following code, I’m expecting either the variable x is put in a read-only memory and hence whatever we do on it via a non constant pointer/reference is without effect and in this case *y should be equal to 0 or the keyword const is just for compile time checking and we can do whatever we want at run-time and in this case both x and *y should be equal to 20. But what I’m getting is that x is equal to 0 and *y to 20 (it seems that y is not pointing to x !!)

#include <iostream>

int main()
{
  const int x = 0 ;
  int *y = (int*) &x ;
  *y = 20 ;

  std::cout << x << std::endl ; //output 0
  std::cout << *y << std::endl ; //output 20

}
noob
  • 774
  • 1
  • 10
  • 23
Soulimane Mammar
  • 1,658
  • 12
  • 20
  • Removing `const` is only _allowed_ in a very narrow context. In general if an object was const when it was created, then it is not valid to cast away its const, because the compiler could have optimized away the object entirely. If it became const while it was passed to another function (`void foo(const &a); int x=10; foo(x);`), it _might_ be valid to cast away the const. – t.niese Feb 08 '19 at 06:51

1 Answers1

2

A nice example of a problem caused by optimization., and also why you should be careful using stuff like that. The main objective of the keywords const is to tell the compiler that this value will not change, and the compiler may (but not must) optimize it out. It is more effecient to just put an assembly instruction that uses the value 20 rather than going to the memory and fetching the actual value, and this is exactly what the compiler did. Because you allowed it. Compiler is not obliged to follow pointers and actually check what you modify. So this is undefined behavior you have here and this is how const works.

Yuri Nudelman
  • 2,874
  • 2
  • 17
  • 24
  • I finally figured out what is happening with this code by printing an other reference to x and the result was 20 it seems that the compiler is generating 0 wherever x appears in the code (behaving like #define x 0 but at run-time) – Soulimane Mammar Feb 08 '19 at 06:40