This question already has answers here:
What is x after “x = x++”?

(17个答案)


3年前关闭。



import java.io.*;
public class test {
    public static void main(String args[]) {
        int a=0, b=6, sum;
        for(int i=0; i<=2; i++) {
            System.out.println(i=i++);
        }
    }
}

输出:0 | 1 | 2。但实际上我认为应该是0 | 2。请解释为什么我错了?先感谢您。

最佳答案

区别在于以下代码行:

System.out.println(i=i++);

i ++是后递增的,这意味着它仅在语句的其余部分之后执行。

因此,它有点像这样:
System.out.println(
  int tempI = i;
  i = tempI;
  tempI = i + 1;
  );

最后,您输出i的值,而之后不使用tempI的值,因此被认为丢失了。

07-28 10:24