postfix一元运算符到底发生了什么?

时间:2016-05-23 07:55:30

标签: java operators unary-operator

我读了一些关于一元算子的帖子: What is the Difference between postfix and unary and additive in java "C - C++" joke about postfix/prefix operation ordering

还有一些。

但是,当值发生变化时,我仍然无法完全理解

例如:

int x = 1;
x = x++;
System.out.print("x = x++ ==> ");
System.out.print(" x = " + x);
System.out.println();
int x = 1;
x = x++ + x++;
System.out.print("x = x++ + x++ ==> ");
System.out.print(" x = " + x);
System.out.println();

输出结果为:

x = x++ ==>  x = 1
x = x++ + x++ ==>  x = 3

因此,在第一个块中x被分配给x,然后递增,但是从不使用该值,否则输出将是x = 2

在第二个块中,如果我理解正确,则在分配之前评估第一个x++,然后评估第二个x++但从未使用过。

如果在第二个块中,x++将在赋值后评估但从未使用过,则输出将为x = 2。如果两者都已使用,则输出为x = 4

我的IDE还指出使用了第一个x++,但未使用第二个<div class="classA classB ClassC"></div>enter image description here

总而言之 - 我仍然对完全增量的时间和方式感到困惑。

1 个答案:

答案 0 :(得分:3)

x = x++ + x++;

假设x = 1,第一个x++返回&#34; 1&#34;作为值,然后它将x增加到2.所以基本上,它将旧值分配回x

第二个x++做同样的事情;它返回x的值,现在为2,然后才将其值增加到3 - 不使用该值。

您的代码相当于:

tmp = x;
x = x + 1;

tmp2 = x;
x = x + 1; // not used

x = tmp + tmp2;

可能有助于您的链接:

相关问题