For below snippet,
#include <iostream>
using namespace std;
void fun(const int *p)
{
int *q = const_cast<int *>(p);
*q = *q * 10;
cout<<"q: "<<q<<"\t Value: "<<*q<<endl;
}
int main()
{
const int a = 10;
const int *z = &a;
fun(z);
cout<<"z: "<<z<<"\t"<<"Address of a: "<<&a<<endl;
cout<<"value at z: "<<*z<<"\t\t value in a: "<<a<<endl;
}
the output produced is
q: 0x7fff65910fcc Value: 100
z: 0x7fff65910fcc Address of a: 0x7fff65910fcc
value at z: 100 value in a: 10
Why the value of a is not modified even though i tried to modify it in fun()?
How come the address of a and the pointer z are same but the values are different?
Is it some kind of undefined behavior with const_cast ?
Yes, your program contains undefined behavior.
This means that you cannot have any expectation on its output. The reason is given by paragraph 7.1.6.1/4 of the C++11 Standard:
Paragraph 5.2.11/7 on
const_cast
contains a further warning: