Incrementor logic

后端 未结 7 2192
醉梦人生
醉梦人生 2020-11-27 05:37

I\'m trying to get deeper with post and pre incrementors but am a bit stuck with the following expression :

public static void main(String[] args) {
    int i         


        
7条回答
  •  悲&欢浪女
    2020-11-27 06:06

    Quoting Java Language Specification, 15.7 Evaluation Order:

    The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

    The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.

    If the operator is a compound-assignment operator (§15.26.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied binary operation.

    So, essentially, i += ++i will remember the old value of i on the left side, before evaluating the right side.

    Remember, evaluation order of operands and precedence of operators are two different things.

    Showing evaluation order, step by step, with saved value in {braces}:

    int i = 0;
    i    = i    += (++i + (i    += 2 + --i) - ++i); // i = 0
    i{0} = i    += (++i + (i    += 2 + --i) - ++i); // i = 0
    i{0} = i{0} += (++i + (i    += 2 + --i) - ++i); // i = 0
    i{0} = i{0} += (1   + (i    += 2 + --i) - ++i); // i = 1
    i{0} = i{0} += (1   + (i{1} += 2 + --i) - ++i); // i = 1
    i{0} = i{0} += (1   + (i{1} += 2 + 0  ) - ++i); // i = 0
    i{0} = i{0} += (1   + (i{1} += 2      ) - ++i); // i = 0
    i{0} = i{0} += (1   + 3                 - ++i); // i = 3
    i{0} = i{0} += (4                       - ++i); // i = 3
    i{0} = i{0} += (4                       - 4  ); // i = 4
    i{0} = i{0} += 0                              ; // i = 4
    i{0} = 0                                      ; // i = 0
    0                                             ; // i = 0
    

    Followup to edits to question

    If we name the initial value I and the constant N:

    int i = I;
    i = i += (++i + (i += N + --i) - ++i);
    

    Then we can see that the values are:

    i{I} = i{I} += ((I+1) + (i{I+1} += N + I) - ((I+1+N+I)+1));
    i{I} = i{I} += (I + 1 + (I + 1 + N + I) - (I + 1 + N + I + 1));
    i{I} = i{I} += (I + 1 + I + 1 + N + I - I - 1 - N - I - 1);
    i{I} = i{I} += I;
    i{I} = I + I;
    i = 2 * I;
    

提交回复
热议问题