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?

Était-ce utile?

La 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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top