0
void main() {

const int a = 10;
const int *b = &a;
int *c = const_cast <int*>(b);
*c = 5;
cout<<a<<" "<<*b<<" "<<*c<<endl; //10 5 5
cout<<&a<<" "<<b<<" "<<c<<endl; //same address
cout<<*(int*)&a<<" "<<*&a<<endl; //5 10
}

what makes type cast affected this? where is the value stored?

  • 7
    It's `int main`, not `void main`. And modifying constant data is undefined behaviour. Don't expect anything. – chris Apr 26 '14 at 17:25
  • `const_cast` should only be used (never, heh) when you *know* the referenced data was not `const`. I.e. if `a` were **not** `const`, then `const_cast`ing the `b` pointer has merit. As written you're violating that. [See it live](http://ideone.com/cutUWq) – WhozCraig Apr 26 '14 at 17:48
  • Your question isn't clear so it's hard to know exactly what information your looking for. – Captain Obvlious Apr 26 '14 at 18:07

1 Answers1

1

The program has undefined behavior: with the const_cast<int*>(b) you remove the const qualifier from an object which actually is const and the assignment to that object may have arbitrary effect.

The observed effects indicate that the implementation replaced uses of a with its immutable value while it dereferences b to determine the value. It could have arbitrary other effect, too, though. For example, a segmentation fault when trying to write a write protected location could be a possible outcome. Well, anything can happen.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380