微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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的副本来确认.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐