序列点和运算符优先级之间的区别?0_o [英] Difference between sequence points and operator precedence? 0_o

查看:59
本文介绍了序列点和运算符优先级之间的区别?0_o的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我举个例子:

a = ++ a;

据说上述声明具有未定义的行为(我已经阅读了有关UB on SO的文章)

The above statement is said to have undefined behaviors ( I already read the article on UB on SO)

但是根据优先级规则,运算符前缀 ++ 的优先级高于赋值运算符 =

but according precedence rule operator prefix ++ has higher precedence than assignment operator =

因此 a 应该先增加,然后再分配回a.所以每个评估都是已知的,为什么要选择UB?

so a should be incremented first then assigned back to a. so every evaluation is known, so why it is UB ?

推荐答案

这里要了解的重要一点是,运算符可以产生值,还可以具有副作用.

The important thing to understand here is that operators can produce values and can also have side effects.

例如, ++ a 产生(评估为) a + 1 ,但是它也具有增加 a 的副作用.对于 a = 5 (计算为5,还将 a 的值设置为5)也是如此.

For example ++a produces (evaluates to) a + 1, but it also has the side effect of incrementing a. The same goes for a = 5 (evaluates to 5, also sets the value of a to 5).

所以您在这里有两个副作用,它们改变了 a 的值,它们都发生在序列点之间(可见分号和上一条语句的结尾).

So what you have here is two side effects which change the value of a, both happening between sequence points (the visible semicolon and the end of the previous statement).

没关系,由于运算符的优先级,两个运算符的评估顺序是明确定义的,因为处理其副作用的顺序仍然是不确定的.

因此,UB.

这篇关于序列点和运算符优先级之间的区别?0_o的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆