++i+i++ evaluation

╄→尐↘猪︶ㄣ 提交于 2019-12-04 16:02:00

问题


Confusion rose because of this post. The author updated his post, and the result became clear. Conclusion: Java evaluates expressions from left to right

Closed!

As evaluation of expression is done from right to left the following code should store 5 in j:

int i=2;
int j=++i+i++;
System.out.println(j);

But I get 6 as the output, which forces me to re-think the right to left evaluation idea. Kindly explain the theory here.


回答1:


int i = 2;
int j = ++i + i++;

is the same as

int i = 2;

// This part is from ++i
i = i + 1;
int left = i; // 3

// This part is from i++
int right = i; // 3
i = i + 1;

int j = left + right; // 3 + 3 = 6

If instead you'd done:

int i = 2;
int j = i++ + ++i;

that would be equivalent to:

int i = 2;

// This part is from i++
int left = i; // 2
i = i + 1;

// This part is from ++i
i = i + 1;
int right = i; // 4


int j = left + right; // 2 + 4 = 6

So the sum is the same, but the terms being summed are different.




回答2:


You get 6 because it's 3 + 3:

  • the first OP is ++i which increments first (to 3) then that value is used
  • next OP is +i which adds 3 again
  • last OP ++ doesn't take part in the addition, but it increments i after using it



回答3:


Your assumption is false. Here's what the documentation says :

All binary operators except for the assignment operators are evaluated from left to right

So

++i+i++

is equivalent to

(++i)+(i++)

where ++i is evaluated first.

This gives

3+3

which is 6 (and i has value 4 after this).




回答4:


The first ++ increments i. The + adds i to itself. i is 3.




回答5:


Where'd you get the idea that it is right-to-left? It is left-to-right.

What are the rules for evaluation order in Java?




回答6:


This how it works, since unary operators have more precedance than binary:

int i=2;
int j =(++i)+(i++);
        ^^^   ^^^ 
         3  +(i++) //The value of i is now 3.
        ^^^   ^^^
         3  +  3   //The value of i is incremented after it is assigned.



回答7:


When evaluating an expression such as a+b, before you can add 'b' to 'a', you need to know what 'a' is. In this case, a is ++i, which is 3, and b is i++ which is 3. Evaluating right-to-left gives 3 + 3 = 6




回答8:


In Java and C#, the evaluation of subexpressions will be done left to right:

int j=++i + i++;

contains the following two subexpressions ++i and i++. These subexpressions will be evaluated in this order so this will translate into:

int j= 3 + 3;

As in Java and C#, the ++i will be executed returning 3 but i will be changed to 3 before the second i++. The second will return the current value of i which is 3 now and after i++ the value of i will be 4.

In C++ this would be undefined.

And in real-world, you do not want to type this code (except for code golfing)



来源:https://stackoverflow.com/questions/16363112/ii-evaluation

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