How to change the constness of a variable in C++?
You should never change the constness of an inherently const
qualified variable!
An const
qualified 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_cast
to 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?
What is happening is Undefined Behavior.
You should not be changing the constness of an const
qualified 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.
Why the result?
In this case since i
is constant probably the compiler inlines the const variable as a part of its optimization and hence the pointer hackery does not affect the value of i
since it already inlined by compiler it simply puts the inlined value wherever i
is encountered in the code.
Note that the compiler does so because you made an contract with the compiler,
Heres my i
and 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…