gpt4 book ai didi

c - 使用 volatile 关键字修改 const 变量

转载 作者:太空狗 更新时间:2023-10-29 15:36:01 24 4
gpt4 key购买 nike

我正在回答 question并制作了这个测试程序。

#include <stdio.h>
int main()
{
volatile const int v = 5;
int * a = &v;
*a =4;
printf("%d\n", v);
return 0;
}

如果没有 volatile 关键字,代码会优化(使用 -O3 apple clang 4.2 编译)var 的变化,它按预期工作并且 const 变量被正确修改。

我想知道更有经验的 C 开发人员是否知道标准的一部分是否表示这是不安全的或 UB。

更新: @EricPostpischil 给了我这个标准引用

A program may not modify its own object defined with a const-qualified type, per C 2011 (N1570) 6.7.3 6: “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.” An external agent may modify an object that has volatile-qualified type, per 6.7.3 7: “An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects

我的程序违反了第一条规则,但我认为第二条规则可能会使程序免于第一条规则。

更新 2:

An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects. Therefore any expression referring to such an object shall be evaluated strictly according to the rules of the abstract machine, as described in 5.1.2.3. Furthermore, at every sequence point the value last stored in the object shall agree with that prescribed by the abstract machine, except as modified by the unknown factors mentioned previously.134) What constitutes an access to an object that has volatile-qualified type is implementation-defined.

如果您查看此引述,您会发现 var 必须根据某些规则进行评估,我还没有通读 5.1.2.3 部分的全部内容,但我相信这可能会有所启发关于这个问题。

最佳答案

这是不安全的,因为不能保证在其他编译器中使用相同的行为。因此,您的代码依赖于编译器,甚至可能依赖于编译器开关。这就是为什么这是个坏主意。

关于c - 使用 volatile 关键字修改 const 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18064722/

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