问题描述
我回答question并提出这个测试程序。
I was answering a question and made this test program.
#include <stdio.h>
int main()
{
volatile const int v = 5;
int * a = &v;
*a =4;
printf("%d\n", v);
return 0;
}
如果没有volatile关键字的code优化VAR之外的变化,它的工作原理是预期和常数变量正确修改(与苹果-O3 4.2铿锵编译)。
Without the volatile keyword the code optimizes (compiled with -O3 apple clang 4.2) the change of the var away, with it works as expected and the const variable is modified correctly.
我在想,如果一个更有经验的C语言开发知道如果有标准的一部分,说这是不安全或UB。
I was wondering if a more experienced C developer knows if there is a part of the standard that says this is unsafe or UB.
更新: @EricPostpischil给了我这个标准的引用
UPDATE: @EricPostpischil gave me this standards quote
一个程序可能无法修改与一个const限定的类型定义自己的对象,每Ç2011(N1570)6.7.3 6:如果试图修改通过使用一个const限定的类型定义的对象与非const限定类型的左值,则行为是不确定的外部代理人可以修改每6.7.3 7具有volatile限定类型的对象,:一个具有volatile限定类型可能的方式来修改对象不明就里的实施或有其他未知的副作用
我的节目打破了第一条规则,但我认为第二个规则可豁免第一个程序。
My program breaks the first rule but I thought that the second rule may exempt a program from the first.
更新2:
具有volatile限定类型的对象可能的方式未知的实施进行修改或者有其他未知的副作用。因此,任何前pression指这样一个对象,应根据抽象机的规则严格评估,如5.1.2.3所述。此外,在每个序列点最后存储在对象中的值应与抽象的机器,prescribed同意,除非提到的previously.134未知因素)什么构成对具有的对象的访问改性volatile限定类型是实现定义的。
如果你看一下这句话,你可以看到VAR必须按照一定的规则进行评估,我没有通过所有段的读 5.1.2.3
但我相信这可能摆脱对这个问题的一些情况。
If you look at this quote you can see the var must be evaluated according to certain rules, I haven't read through all of section 5.1.2.3
but I believe that this may shed some light on the issue.
推荐答案
这是不安全的,因为同样的行为不能保证在其他编译器中使用。所以,你的code是编译器相关的,甚至可能是编译器开关依赖。这就是为什么它是一个坏主意。
It is unsafe because the same behavior cannot be guaranteed for use in other compilers. So your code is compiler-dependent and may even be compiler switch dependent. That's why it's a bad idea.
这篇关于修改一个const变量,volatile关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!