Following is my code
const int i = 10;
cout<<i<<"\n";
int *ip = (int*)&i;
*ip = 20;
cout<<i<<"\n";
I was expecting output as 10 and 20.
But I am getting output as 10 and 10.
I am able to compile the program and I don’t get any error at compile time or runtime but not getting the expected outcome. If I have removed the constness of the variable i why the new value is not assigned to it?
I would be grateful If somebody could explain whats happening and what can be done to achieve my expected result.
You should never change the constness of an inherently
constqualified variable!An
constqualified variable is declared with the aim that it should not be modified after it is initialized. By attempting to change the constness you break the contract with the compiler.If you need to modify a variable, simply do not declare it as
const.Note that C++ provides
const_castto remove or add constness to a variable. But, while removing constness it should be used to remove constness off a reference/pointer to something that was not originally constant.What is happening is Undefined Behavior.
You should not be changing the constness of an
constqualified variable, If you do so through some pointer hackery what you get is Undefined behavior.In case of undefined behavior the standard does not mandate compilers to provide a compile time diagnostic.Note though that some compilers may warn you if you compile with highest warning level.
Also, undefined behavior means that when you run the program anything can happen and the compiler might show you any result and it does not warrant an explanation.
In this case since
iis constant probably the compiler inlines the const variable as a part of its optimization and hence the pointer hackery does not affect the value ofisince it already inlined by compiler it simply puts the inlined value whereveriis encountered in the code.Note that the compiler does so because you made an contract with the compiler,
Heres my
iand it will never be changed throughout the lifetime of my program.The compiler is free to apply whatever optimizations it can want as long as it adheres to the contract and it does so in this case.