简体   繁体   English

什么时候确实发生postfix一元运算符?

[英]When exactly does postfix unary operator happen?

I read a few post regarding unary operator: What is the Difference between postfix and unary and additive in java "C - C++" joke about postfix/prefix operation ordering 我读了一些关于一元运算符的帖子: java “C - C ++”中关于postfix / prefix操作排序的 postfix和unary以及添加剂有什么区别

And a few more. 还有一些。

However, I still don't understand exactly when the value is changed. 但是,我仍然不清楚何时更改值。

For example: 例如:

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

The output is: 输出是:

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

So in the first block x is assigned to x and afterwards incremented, but the value is never used, otherwise the output would have been x = 2 . 所以在第一个块中x被赋值给x然后递增,但是从不使用该值,否则输出将是x = 2

In the second block, if I understand correctly, the first x++ is evaluated before the assignment and the second x++ is evaluated afterwards but is never used. 在第二个块中,如果我理解正确,则在赋值之前评估第一个x++ ,然后对第二个x++进行求值,但从不使用。

If in the second block both x++ would have been evaluated after the assignment but never used, the output would have been x = 2 . 如果在第二个块中, x++将在赋值后进行评估但从未使用过,则输出将为x = 2 If both have been used, the output would have been x = 4 . 如果两者都已使用,则输出将为x = 4

My IDE also indicated that the first x++ is used, but the second is not used: 我的IDE还指出使用了第一个x++ ,但没有使用第二个: 在此输入图像描述

So to conclude - I'm still confused about when and how exactly the increment is done. 所以得出结论-我仍然迷茫的时候, 正是增量完成的。

At the line 在线

x = x++ + x++;

Assuming x = 1 , the first x++ returns "1" as the value, and then it increments x to 2. So basically, it's assigning the old value back to x . 假设x = 1 ,第一个x++返回“1”作为值, 然后它将x递增到2.所以基本上,它将旧值赋给x

The second x++ does the same; 第二个x++做同样的事情; it returns the value of x , which is now 2, and only then increments its value to 3 - that value, is not used. 它返回x的值,现在为2,然后才将其值增加到3 - 不使用该值。

Your code is equivalent to: 您的代码相当于:

tmp = x;
x = x + 1;

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

x = tmp + tmp2;

Links that may help you: 可能对您有所帮助的链接:

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

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