简体   繁体   English

该表达式如何计算

[英]How does this expression will be calculated

I have an expression with compound assignment as 我有一个带有复合赋值的表达式

x += 2*5 x + = 2 * 5

so how it will be evaluated is it 所以它会如何评估

x = (x + 2) * 5 x =(x + 2)* 5

or 要么

x = x + (2 * 5) x = x +(2 * 5)

and why? 为什么呢?

An expression of the form 形式的表达

x += expr;

is equivalent to 相当于

x = x + (expr);

So in this case it's 所以在这种情况下

x = x + (2 * 5);

It would be very weird and confusing if the current value of x was used for part of the expression implicitly. 如果x的当前值被隐式地用于表达式的一部分,那将是非常奇怪和令人困惑的。

Any expression in the form of var op= expr is evaluated to var = var op expr . 任何形式为var op= expr都将求值为var = var op expr This is defined in the java specification 15.26.2 Compound Assignment Operators . 这是在Java规范15.26.2复合赋值运算符中定义的

I see the phrase "operator precedence" mentioned, and I believe this is confusing the issue. 我看到提到了“操作员优先”一词,并且我相信这使这个问题感到困惑。 Consider this: 考虑一下:

x *= a + b;

Even though * has a higher precedence than + , this is still evaluated as 即使*的优先级比+ ,这仍被评估为

x = x * (a + b)

The full explanation is given in JLS 15.26.2 Compound Assignment Operatos : 完整的解释在JLS 15.26.2复合赋值Operatos中给出

E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)) , where T is the type of E1 , except that E1 is evaluated only once E1 op = E2等效于E1 =(T)(((E1)op(E2)) ,其中TE1的类型,只是E1仅被评估一次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM