以下示例使我的理解更加混乱。我无法理解如何修改本地 const 变量。请帮助我理解同样的事情。
/* Compile code without optimization option */
// volatile.c
#include <stdio.h>
int main(void)
{
const int local = 10;
int *ptr = (int*) &local;
printf("Initial value of local : %d \n", local);
*ptr = 100;
printf("Modified value of local: %d \n", local);
return 0;
}
$ gcc 易失性.c -o 易失性 –保存临时文件
$ ./不稳定
本地初始值:10
local的修改值:100
这简直就是未定义的行为 https://en.wikipedia.org/wiki/Undefined_behavior如果我们看一下 C99 草案标准部分6.7.3
类型限定符段落4它说:
If an attempt is made to modify an object defined with a const-qualified type through use
of an lvalue with non-const-qualified type, the behavior is undefined. If an attempt is
made to refer to an object defined with a volatile-qualified type through use of an lvalue
with non-volatile-qualified type, the behavior is undefined.115)
所以你不能对结果有任何期望,你不应该这样做。
如果我们看一段2它说:
The properties associated with qualified types are meaningful only for expressions that
are lvalues.114)
和脚注114
says:
该实现可以将一个非易失性的 const 对象放置在只读区域中
贮存。此外,如果从未使用过此类对象的地址,则实现不需要为其分配存储空间。
一般来说,实施不必使const变量只读但可能会,但正如 R.. 指出的那样,将自动变量放入只读存储器中会很困难。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)