在 C 中,可以通过指针修改 const 变量吗? [英] In C, can a const variable be modified via a pointer?
问题描述
我在我的代码中写了一些类似的东西
I wrote some thing similar to this in my code
const int x=1;
int *ptr;
ptr = &x;
*ptr = 2;
这是否适用于所有编译器?为什么 GCC 编译器没有注意到我们正在改变一个常量变量?
Does this work on all compilers? Why doesn't the GCC compiler notice that we are changing a constant variable?
推荐答案
const
实际上并不意味着恒定".C 中的常量"具有在编译时确定的值;文字 42
就是一个例子.const
关键字真正意味着只读.考虑,例如:
const
actually doesn't mean "constant". Something that's "constant" in C has a value that's determined at compile time; a literal 42
is an example. The const
keyword really means read-only. Consider, for example:
const int r = rand();
r
的值直到程序执行时才确定,但是 const
关键字意味着您不能修改 r
初始化之后.
The value of r
is not determined until program execution time, but the const
keyword means that you're not permitted to modify r
after it's been initialized.
在您的代码中:
const int x=1;
int *ptr;
ptr = &x;
*ptr = 2;
赋值 ptr = &x;
是一个约束违规,这意味着需要一个符合标准的编译器来抱怨它;您不能合法地将 const int*
(指向 const int 的指针)值分配给非常量 int*
对象.如果编译器生成一个可执行文件(它不需要这样做;它可以拒绝它),那么该行为不是由 C 标准定义的.
the assignment ptr = &x;
is a constraint violation, meaning that a conforming compiler is required to complain about it; you can't legally assign a const int*
(pointer to const int) value to a non-const int*
object. If the compiler generates an executable (which it needn't do; it could just reject it), then the behavior is not defined by the C standard.
例如,生成的代码实际上可能将值 2
存储在 x
中——但随后对 x
的引用可能会产生值1
,因为编译器知道x
在初始化后不能被修改.它知道,因为你告诉它,通过将 x
定义为 const
.如果你对编译器撒谎,后果可能会很糟糕.
For example, the generated code might actually store the value 2
in x
-- but then a later reference to x
might yield the value 1
, because the compiler knows that x
can't have been modified after its initialization. And it knows that because you told it so, by defining x
as const
. If you lie to the compiler, the consequences can be arbitrarily bad.
实际上,可能发生的最糟糕的事情是程序按照您的预期运行;这意味着您有一个很难检测到的错误.(但你应该得到的诊断结果将是一个很大的线索.)
Actually, the worst thing that can happen is that the program behaves as you expect it to; that means you have a bug that's very difficult to detect. (But the diagnostic you should have gotten will have been a large clue.)
这篇关于在 C 中,可以通过指针修改 const 变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!