c – 可以将volatile volatile的间接变化视为未定义的行为吗?

易失性写入易失性const是否会引入未定义的行为?如果我在写作时放弃挥发怎么办?

volatile const int x = 42;
const volatile int *p = &x;
*(volatile int *)p = 8; // Does this line introduce undefined behavior?
*(int *)p = 16; // And what about this one?

Compilable code

解决方法

当您尝试修改“初始”const对象时,它是未定义的行为(对于两个语句).从C11(N1570)6.7.3 / p6类型限定符(强调我的):

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.

因此后面的陈述,即:

*(int *)p = 16;

对于第二个短语也是未定义的(它是“双UB”).

我相信C的规则是相同的,但不要拥有C 14的副本来确认.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...