Search code examples
javapostfix-operatorprefix-operator

Multiple postfix and prefix operations in single line


int i=0;
int j = --i;

int k = i++ + --i + i-- + j-- + --i + i;

System.out.print("k= "+k);  // k=-10

I cant seem to understand how come the value of k is -10 ?

Here is what i feel should have happened. The result should have been -5 as per my calculations.

Expression                       |Evaluation                | Current Values
                                 |                          | i=0  ,j=-1   
i++                              | 0                        | i=1  ,j=-1   
i++ + --i                        | 0 + 0                    | i=0  ,j=-1   
i++ + --i + i--                  | 0 + 0 + 0                | i=-1 ,j=-1   
i++ + --i + i-- + j--            | 0 + 0 + 0 + -1           | i=-1 ,j=-2   
i++ + --i + i-- + j-- + --i      | 0 + 0 + 0 + -1 + -2      | i=-2 ,j=-2   
i++ + --i + i-- + j-- + --i + i; | 0 + 0 + 0 + -1 + -2 + -2 | i=-2 ,j=-2   

Please correct me if I am wrong.

*After correcting my mistake of taking i as 0 instead of -1 *

The expression is now evaluating as -10 (-1 + -1 + -1 + -1 + -3 + -3). Thanks.

Expression                       |Evaluation                   | Current Values
                                 |                             | i=-1, j=-1
i++                              | -1                          | i= 0, j=-1
i++ + --i                        | -1 + -1                     | i=-1, j=-1
i++ + --i + i--                  | -1 + -1 + -1                | i=-2, j=-1
i++ + --i + i-- + j--            | -1 + -1 + -1 + -1           | i=-2, j=-2
i++ + --i + i-- + j-- + --i      | -1 + -1 + -1 + -1 + -3      | i=-3, j=-2
i++ + --i + i-- + j-- + --i + i; | -1 + -1 + -1 + -1 + -3 + -3 | i=-3, j=-2

Solution

  • If you correctly do decrements and increments you'll get the following: int k = -1 + (-1) + (-1) + (-1) + (-3) + (-3) which is equal to -10