Why is the operator precedence not followed here? [duplicate]

守給你的承諾、 提交于 2020-06-24 06:03:29

问题


In this code:

int y = 10;
int z = (++y * (y++ + 5)); 

What I expected

First y++ + 5 will be executed because of the precedence of the innermost parentheses. So value of y will be 11 and the value of this expression will be 15. Then ++y * () will be executed. So 12 * 15 = 180. So z=180

What I got

z=176

This means that the VM is going from left to right not following operator precedence. So is my understanding of operator precedence wrong?


回答1:


The expression (++y * (y++ + 5)); will be placed in a stack something like this:

1. [++y]
2. [operation: *]
3. [y++ + 5] // grouped because of the parenthesis

And it will be executed in that order, as result

1. 10+1 = [11] // y incremented 
2. [operation: *]
3. 11+5 = [16] // y will only increment after this operation

The the expression is evaluated as

11 * 16 = 176



回答2:


First y++ + 5 will be executed because of the precedence of the innermost parentheses

Precedence and evaluation order are not the same thing. All binary expressions except the assignment expression are evaluated left-to-right. Therefore y++ is evaluated before the parenthesized expression on the right.




回答3:


The parentheses just describe how the sub-expressions will be grouped together. Parenthesizing doesn't mean it will be evaluated first. Rather, the rule in java is evaluate each sub-expression strictly from left to right.

Always remember that the order of evaluation has absolutely nothing to do with operator precedence and associativity.

Java Oracle documentation says that:

15.7. Evaluation Order

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

Therefore, the expression (++y * (y++ + 5)) will be evaluated as

temp1 = ++y = 11
temp2 = y++ + 5 = 11 + 5 = 16 
z = temp1*temp2 = 11*16 = 176  

Further reading: Eric Lippert's blog, Precedence vs Associativity vs Order, explained in detailed about precedence, associativity and order of evaluation. Though this blog addresses c# but equally valid for java too.




回答4:


  1. First will be executed ++y. y will be 11.
  2. Then will be executed y + 5 (actually y++ + 5 can be written as 5 + y++ which is interpreted as (5 + y) and then y++). z will become 11 * 16 = 176.
  3. y will be 12 after the calculation finishes.



回答5:


The calculation is going on following order

 z= (++10 * (10++ + 5))
 z= (11 * (11 + 5))//++ (prefix or postfix) has higher precedence than + or *
 z= (11 * 16)
 z= 176 


来源:https://stackoverflow.com/questions/29162301/why-is-the-operator-precedence-not-followed-here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!