++ i + i ++评估 [英] ++i+i++ evaluation

查看:147
本文介绍了++ i + i ++评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


混乱因而上升这篇文章。作者更新了他的帖子,结果变得清晰。
结论:Java评估从左到右的表达式

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



已关闭!



表达式的评估是从从右到左完成的,以下代码应存储 5 in j

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);

但我得 6 作为输出,这迫使我重新想想从右到左评估的想法。请在此解释理论。

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

推荐答案

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

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

如果您已完成:

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

相当于:

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.

这篇关于++ i + i ++评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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