-2

Look at this program:

int main(){
    const int a_const=10;
    int * const a=const_cast<int * const>(&a_const);
    *a=5;
}

So the address of a_const and the pointer a have the same value. But changing the value of what a is pointing to, doesn't a_const.

Cœur
  • 37,241
  • 25
  • 195
  • 267
GraphLearner
  • 179
  • 1
  • 2
  • 11

1 Answers1

5

The behaviour of your program is undefined. It appearing to be possible is a manifestation of that undefined behaviour.

You are not allowed to attempt to change the value of a variable that was declared as const, by using a non-const pointer (or reference) that has been obtained as a result of a const_cast.

(If it appears to work in this case, try the equivalent with a read only-string literal - that will cause a crash on very many platforms.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483