I was experimenting with const pointers.
#include <bits/stdc++.h>
using namespace std;
int main()
{
const int i=4;
const int *const p=&i;
int *p1=const_cast<int*>(p);
*p1=10;
cout<<p<<" "<<p1<<" "<<&i<<endl;
cout<<i<<" "<<*p1<<endl;
}
I know that using const_cast
causes undefined behavior when the object in question is const(like i in this case). But after executing the code the value of i remains 4 and value of *p1
is 10 while the value of p
p1
ans &i
are the same, i.e , p1 is pointing to location of i but dereferencing it gives some other value. How does it happen?
Compiled with: g++ 4.8.1 and clang++ 3.3.