Pre- and postincrement in Java

后端 未结 6 1703
不思量自难忘°
不思量自难忘° 2021-01-17 13:48

I just wanted to create a little Java-Puzzle, but I puzzled myself. One part of the puzzle is:

What does the following piece of code do:



        
6条回答
  •  心在旅途
    2021-01-17 14:39

    i += ++i + i++ + ++i;

    1. i=1 at start
    2. i += X -> i = i + X -> i = 1 + X (so lets count X)
    3. ++i will be incremented to 2 and return 2
    4. i++ will return 2 and then be incremented to 3
    5. ++i will be incremented from 3 to 4 and return 4
    6. X = 2 + 2 + 4 = 8

    So i = 1 + 8 -> i=9


    You would get 12 if your code would be something like this

    int i = 1;
    int tmp = ++i + i++ + ++i;  
    i += tmp;
    

    because then your code would be i=1, and after calculating tmp i would be i=4, then i+=tmp -> i=4+8=12

提交回复
热议问题