在C语言中,可以一个const变量通过指针进行修改? [英] In C, can a const variable be modified via a pointer?
问题描述
我写了类似这样的一些东西在我的code
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?
推荐答案
常量
其实并不意味着常量。东西是常量用C具有的在编译时确定的值;文字 42
就是一个例子。在常量
关键字的真正含义是只读的。举个例子:
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();
的研究
没有确定,直到程序执行时间的价值,但常量
关键字意味着你不允许修改研究
它的初始化之后。
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.
在您的code:
const int x=1;
int *ptr;
ptr = &x;
*ptr = 2;
分配 PTR =安培; X;
是约束违反的,也就是说,一个符合标准的编译器需要抱怨;你不能合法地分配 const int的*
(指向INT常数)值,以一个非const 为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.
例如,生成code实际上可能存储在值 2
X
- 但随后稍后参考 X
可能产生的价值 1
,因为编译器的知道的是 X
不能被初始化后修改。而且它知道,因为你告诉它的话,通过定义 X
为常量
。如果你骗编译器,后果可以任意坏的。
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屋!