If I have a constant variable, is it stored in a seperate memory space from non-constant variables? I have encounter some odd in this program.
//--------assign a const value to non-const value-------
const int cst_a = 5;
int* ptra = const_cast<int*>(&cst_a);
cout<<&cst_a<<" "<<ptra<<endl; // same address
*ptra = 6;
cout<<*ptra<<" "<<cst_a<<endl; // same address with different value
//--------assign a non-const value to const value-------
int b = 50;
const int* cst_ptr_b = &b;
cout<<cst_ptr_b<<" "<<&b<<endl; // also same address
b = 55;
cout<<b<<" "<<*cst_ptr_b<<endl; // same address with same value
return 0;
In the first case, &cst_a and ptra has the same memory address, but their value can change seperately. In the second case, cst_ptr_b and &b are also same address, but their value change symetrically. Why?
It may be stored in a memory area that can’t be modified. Because of this, your
const_castresults in undefined behavior.