运算符优先级和关联性 [英] Operator Precedence and associativity

查看:97
本文介绍了运算符优先级和关联性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个表达式具有两个具有相同优先级的运算符时,该表达式将根据其关联性进行求值.我想知道以下工作原理:

When an expression has two operators with the same precedence, the expression is evaluated according to its associativity. I want to know how the following works:

i=b + b + ++b

i这是4 因此++b并没有更改前2个b值,而是先执行,因为执行是从左到右.

i here is 4 So ++b didn't change the first 2 b values, but it executed first, because the execution is from left to right.

但是,在这里:

int b=1;
i= b+ ++b + ++b ;

i是6

根据关联性,我们应该执行第三个b,因此它应该是: 1+ (++1) + ( ++1 should be done first).这样就变成了: 1 ++++ 1 + 2 = 5 但是,这是不对的,那么它如何工作?

According to associativity, we should execute the 3rd b so it should be: 1+ (++1) + ( ++1 should be done first). so it becomes: 1 + ++1 + 2 =5 However, this is not right, so how does this work?

推荐答案

您正在将优先级执行顺序混淆.

示例:

a[b] += b += c * d + e * f * g

优先级规则规定*+之前在+=之前.关联性规则(优先级规则的一部分)规定*是左关联的,而+=是右关联的.

Precedence rules state that * comes before + comes before +=. Associativity rules (which are part of precedence rules) state that * is left-associative and += is right-associative.

优先/关联规则基本上定义了隐式括号的应用,将上述表达式转换为:

Precedence/associativity rules basically define the application of implicit parenthesis, converting the above expression into:

a[b] += ( b += ( (c * d) + ((e * f) * g) ) )

但是,此表达式仍然是从左到右求值的.

However, this expression is still evaluated left-to-right.

这意味着表达式a[b]b的索引值将使用执行b += ...之前的b值.

This means that the index value of b in the expression a[b] will use the value of b from before the b += ... is executed.

对于更复杂的示例,混合使用+++=运算符,请参见问题 Incrementor logic ,以及有关其工作原理的详细答案.

For a more complicated example, mixing ++ and += operators, see the question Incrementor logic, and the detailed answer of how it works.

这篇关于运算符优先级和关联性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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