Post and Pre increment operators

后端 未结 7 1095
面向向阳花
面向向阳花 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:25

    The solution can be understood from this example

    public static void main(String[] args) {
        int i = 0;
        i = i++;
        System.out.println("i is" + i);
    }
    /* The output is "i is 0" */
    

    Hence from this line,

    i = i++ + f1(i); 
    

    Your i is still 1 and obviously the function is going to return 0. Which is again stored in i and hence the value 1. Instead of the updated value of i being stored in i, you are overriding it by the assignment operator.

提交回复
热议问题