gpt4 book ai didi

关于使用指针修改 const 变量的困惑

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:36 24 4
gpt4 key购买 nike

以下示例使我的理解更加困惑。我无法理解如何在本地修改 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 volatile.c -o volatile –save-temps

$./ volatile

本地初始值:10

local的修改值:100

最佳答案

这就是undefined behavior如果我们查看 C99 草案标准部分 6.7.3 Type qualifiers paragraph 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 说:

The implementation may place a const object that is not volatile in a read-only region of storage. Moreover, the implementation need not allocate storage for such an object if its address is never used.

一般来说,实现不必使常量变量只读,但它可能但正如 R.. 指出的那样,将自动变量放入只读存储器中会很难。

关于关于使用指针修改 const 变量的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25873289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com