Incrementor logic

后端 未结 7 2194
醉梦人生
醉梦人生 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:00

    I suggest the following: format the code differently, so that there's only 1 statement per line, e.g.

    @Test
    public void test() {
        int i = 0;
        i = 
        i+=
        (
        ++i 
        + 
        (
        i+=
        2 
        + 
        --i
        ) 
        -
        ++i
        );
        System.out.println(i); // Prints 0 instead of 5
    }
    

    Then run it under the debugger and press F5 ("Step into") always. This will help you to understand in which order items get evaluated:

    1. int i=0;
    2. i=: ... (needs to wait for result of calculation A)
    3. i+= ... (needs to wait B)
    4. ++i: i=1
    5. i+= ... (needs to wait C)
    6. 2+
    7. --i: i=0
    8. ...: i=3 (result for wait C)
    9. -
    10. ++i: i=4 and operand of - is also 4
    11. ...: i=0 (result for wait B)
    12. ...: i=0 (result for wait A)

    Line 10 will always make the result of line 3 0, so the initial value of i will never be changed by the whole operation.

提交回复
热议问题