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

标签 c constants volatile undefined-behavior

我正在回答 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/

相关文章:

c++ - 可以在头文件中声明 const vector 吗?

c# - 锁变量应该声明为 volatile 吗?

c - 为什么声明 unsigned char "Volatile"会使其与 "non-volatile"unsigned char 不兼容?

c - 寄存器和 volatile 有什么区别?什么时候使用使用哪一个? volatile 寄存器变量的含义是什么?

c - 从 C 函数返回字符串

c - 如何使用 gcc 编译器 tricore v3.4.6 在 C 中 printf a sint32?

C - 包含整数和字符串的文件(除法问题)

ios - 快速全局常量 : cannot use another constant for initialization

c - 替换(不修改) 'const' 值,合法吗?

c - 从 SCANF 返回 EOF