Value pointed by pointer and the variable are different !!!!!!

Hello everbody...
Today i confronted with a new kind of problem. The value pointer by pointer and the varaible are coming out to be different..
Here is the code for it..

#include<iostream.h>
main()
{
const int i=10;
int *p=const_cast<int *>(&i);
*p=100;
cout<<i<<endl<<*p;
}

expected output is

100
100

and the output comes out to be as

10
100

why this kind of behaviour ?? Help would be appreciated..
yeah i is a const ...but as we can see the output the value pointed by pointer p is equal to 100 and by i , it is equal to 10 .But at the same time pointer p is holding the memory location of i.so how can the same memory location can have two different values..

One more thing i would like to add here .It is that many of us would think that value of const is stored in the sysmbol table in C++ ...but here we are taking the address of const so forcing it to store in the memory by the lne number 5
int *p=const_cast<int *>(&i);
yeah i is a const ...but as we can see the output the value pointed by pointer p is equal to 100 and by i , it is equal to 10 .But at the same time pointer p is holding the memory location of i.so how can the same memory location can have two different values..
That's the result of undefined behaviour

It is that many of us would think that value of const is stored in the sysmbol table in C++ ...but here we are taking the address of const so forcing it to store in the memory by the lne number 5
I'm not sure if I understand this, could you be more clear?
First put the code into code tags not quote or output tags.
Bazzy is right when he says that it is undefined behavior. I don't even know why this question is being asked because a constant value cannot be manipulated through a pointer. Even though you perform a cast to force the nonconst pointer to store the address, that does not enable you to change its value.
I also do not understand what you mean in your second comment. So I will be frank: no matter what tricks you may try to pull on the compiler, you cannot and never will be able to manipulate a const value. That is the point.
It all comes down to the fact that the compiler is allowed to optimize away the
memory access since it "knows" that i is 10 and can never be changed. Hence

cout << i;

is actually compiled as

cout << 10;

closed account (1yR4jE8b)
Exactly, the compiler optimizes away any memory references to i by inserting the value instead.

When you use the const cast, to change the "value of" i, you are forcing the compiler to allocate memory for i and it's this seperate variable that is being changed, not the const value.
Topic archived. No new replies allowed.