Post和Pre增量运算符

zig*_*ggy 8 java scjp ocpjp

当我运行以下示例时,我得到输出0,2,1

class ZiggyTest2{

        static int f1(int i) {  
            System.out.print(i + ",");  
            return 0;  
        } 

        public static void main(String[] args) {  
            int i = 0;  
            int j = 0;  
            j = i++;   //After this statement j=0 i=1
            j = j + f1(j);  //After this statement j=0 i=1
            i = i++ + f1(i);  //i++ means i is now 2. The call f1(2) prints 2 but returns 0 so i=2 and j=0
            System.out.println(i);  //prints 2?
        } 
    } 
Run Code Online (Sandbox Code Playgroud)

我不明白为什么输出是0,2,1而不是0,2,2

mel*_*lik 5

如果我们扩展i = i++ + f1(i)声明,我们会得到类似的内容

save the value of i in a temp variable, say temp1 // temp1 is 1
increment i by one (i++)                          // i gets the value 2
execute f1(i), save return value in, say temp2    // temp2 is 0, print 2
assign temp1 + temp2 to i                         // i becomes 1 again
Run Code Online (Sandbox Code Playgroud)

我想主要步骤可以如上所述进行总结.


Jig*_*shi 3

 i = i++ + f1(i);  
Run Code Online (Sandbox Code Playgroud)

i++意思i就是现在2。调用f1(i)打印2但返回 0i=2所以j=0

在此之前i = 1,现在想象一下f1()调用并替换为 0

所以

i = i++ + 0;
Run Code Online (Sandbox Code Playgroud)

现在会是

i = 1 + 0 // then it will increment i to 2 and then (1 +0) would be assigned back to `i`
Run Code Online (Sandbox Code Playgroud)

用更简单的话来说(来自这里@Piotr)

“i = i++”大致翻译为

int oldValue = i; 
i = i + 1;
i = oldValue; 
Run Code Online (Sandbox Code Playgroud)

另一个这样的例子: