Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

constants - How to change the constness of a variable in C++?

Following is my code

const int i = 10;
cout<<i<<"
";
int *ip = (int*)&i;
*ip = 20;
cout<<i<<"
";

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...