-3
const int *a = new int(100);
int *ptr = (int*) a;
cout << *a << endl;
*ptr = 1000;
cout << *a << endl;

const int b = 100;
int *c = (int*)&b;
*c = 200;
cout << &b << " " << b << endl;
cout << c << " " << *c << endl;

print out

  1. While I use *ptr, I can change the const data *a. Why?
  2. Both the address of b and *c are the same, but the data are different. Why?
  • 8
    This is a problem `(int*)&b;` as your C-style cast will remove the `const` qualifier, so you are modifying a `const` variable which is [undefined behavior](https://stackoverflow.com/questions/2006161/changing-the-value-of-const-variable-in-c). This is why you should use [`static_cast` instead of C-style casts](https://stackoverflow.com/questions/1609163/what-is-the-difference-between-static-cast-and-c-style-casting) because you'd realize you are casting away the `const`. – Cory Kramer Jul 27 '17 at 14:28
  • Second time this is asked today https://stackoverflow.com/questions/45341109/c-forced-conservation-from-const-int-to-int – Bo Persson Jul 27 '17 at 14:57

1 Answers1

2

While I use *ptr, I can change the const data *a. Why?

Because your program is causing undefined behavior. You lied to the compiler that b is non-const by casting const-ness away from the pointer produced by &b, but writing to that pointer on the *c = 200 line is undefined behavior.

Both the address of b and *c are the same, but the data are different. Why?

It happens for the same reason: the behavior is undefined.

As for the real-life scenario when this would happen, I would speculate that the compiler has optimized out the read of b, because you promised it that b is const. However, the compiler found a clever way of getting back at you by replacing a read of the actual b with the output of a constant that has been assigned to b originally.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523