Reputation: 700
While I was learning about const variables in c++, I tried this :
#include <iostream>
int main()
{
const int p = 20;
int* a = const_cast<int*>(&p);
*a = 10;
std::cout<<"Value at a: "<<(*a)<<std::endl;
std::cout<<"Value of p: "<<p<<std::endl;
std::cout<<"Their addresses : "<<std::endl;
std::cout<<a<<" "<<&p<<std::endl;
return 0;
}
and it produces the output:
Value at a: 10
Value of p: 20
Their addresses :
0x7fff4646d7d4 0x7fff4646d7d4
Seemingly I assigned the value 10 to the memory address of p, but their values come out different. Why is it so?
Upvotes: 5
Views: 118
Reputation: 110658
Attempting to modify an object that was originally declared const
gives you undefined behaviour.
§7.1.6.1/4 [dcl.type.cv] Except that any class member declared
mutable
can be modified, any attempt to modify aconst
object during its lifetime results in undefined behavior.
Chances are, your compiler is replacing all occurences of p
in your code with the value 20
, since you have promised that it will not change. So the line that prints p
has changed to:
std::cout<<"Value of p: "<<20<<std::endl;
So it prints 20
regardless of whether you modified the original object. Of course, since you have undefined behaviour, this kind of reasoning is fruitless and you should not invoke undefined behaviour in your program.
Upvotes: 9