加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:35:52 所属栏目:百科 来源:网络整理
导读:易失性写入易失性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 o
易失性写入易失性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的副本来确认.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读