Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top