marsarden wrote:
here is the code:
int main()
{
const int a = 1;
int *p = const_cast<int*>(&a);
*p = 2;
cout << "value a=" << a << endl;
cout << "value *p=" <<*p << endl;
cout << "address a="<<&a << endl;
cout << "address p="<<p << endl;
}
the result like:
value a=1
value *p=2
address a=0012FED4
address p=0012FED4
why the same memory address has different value?
The boilerplate answer is, your program has undefined behaviour
as soon as it attempts to change the value of a constant object;
after that anything can happen.
A more advanced asnwer, involving guesswork, is that the compiler
creates the code that uses the 'a's value (1) defined at the time
of its creation, instead of the current value (which you may have
changed by breaking the rules of the language) when you ask the
value to be output. Hey, says the compiler, the object is const,
it's not going to change, why bother retrieving its value every
time, I will just use the value it was initialised with... And
the code is created to ouptut 1 instead of 'a'. Now, *p cannot
be given the same treatment, since it's *not* const. So, the
compiler generates the code that does in fact retrieve the actual
value (which you managed to change) to be printed.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask