Incrementor logic

后端 未结 7 2193
醉梦人生
醉梦人生 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 05:48

    Ok, let's break down every thing:

    int i = 0; // i = 0, no big deal
    

    Then starting into the most inner parenthesis:

    (i+=2 + --i)
    
    • it first decrement i and use the result (-1)
    • then add 2 (-1+2=1)
    • and add the result to i (which is 0 at the start of the operation) (0+1=1=i)

    At the end, the first decrement is ignored by the reassignation.

    Next parenthesis:

    i+= (++i + previous_result - ++i)
    
    • it increase the i ( with ++i) at two points
    • then the operation becomes (i+1) + previous_result - (i+2) (notice how the increment are not simultaneous) that gives 2 + 1 - 3 = 0.
    • the result of the operation is added to the initial i (0)

    Again the increment will get discard by the reassignation.

    finally:

    i = previous_result
    

    Which gives 0 :)

提交回复
热议问题