如何在 C++ 中更改变量的常量?

2022-01-23 00:00:00 constants c++

以下是我的代码

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

我期望输出为 1020.
但我得到的输出为 1010.

I was expecting output as 10 and 20.
But I am getting output as 10 and 10.

我能够编译程序,并且在编译时或运行时没有收到任何错误,但没有得到预期的结果.如果我删除了变量 i 的常量,为什么不给它分配新值?

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.

推荐答案

如何在 C++ 中改变变量的常量?

您不应该更改固有的 const 限定变量的常量!
声明一个 const 限定变量的目的是在初始化后不应对其进行修改.通过尝试更改常量,您违反了与编译器的合同.

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.

如果你需要修改一个变量,不要将它声明为const.

If you need to modify a variable, simply do not declare it as const.

请注意,C++ 提供了 const_cast 来删除或添加常量到变量.但是,在移除 constness 时,它应该用于移除指向最初不是常量的引用/指针的 constness.

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.

发生了什么?

正在发生的是未定义的行为.

你不应该改变 const 限定变量的常量,如果你通过一些指针hackery 这样做,你得到的是未定义的行为.

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.

为什么会这样?

在这种情况下,由于 i 是常量,因此编译器可能会将 const 变量内联为优化的一部分,因此指针hackery 不会影响 i 的值,因为它已经被编译器内联,它只是将内联值放在代码中遇到 i 的任何地方.

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,

这是我的 i,它在我的程序的整个生命周期内都不会更改.

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.

相关文章