Post and Pre increment operators

后端 未结 7 1038
面向向阳花
面向向阳花 2021-01-17 21:43

When i run the following example i get the output 0,2,1

class ZiggyTest2{

        static int f1(int i) {  
            System.out.print(i + \",\");  
               


        
7条回答
  •  广开言路
    2021-01-17 22:15

     i = i++ + f1(i);  
    

    i++ means i is now 2. The call f1(i) prints 2 but returns 0 so i=2 and j=0

    before this i = 1 , now imagine f1() called and replaced with 0

    so

    i = i++ + 0;
    

    now it would be

    i = 1 + 0 // then it will increment i to 2 and then (1 +0) would be assigned back to `i`
    

    In Simpler words (from here @ Piotr )

    "i = i++" roughly translates to

    int oldValue = i; 
    i = i + 1;
    i = oldValue; 
    

    Another such Example :

    • The same fundamental works here

提交回复
热议问题