In Java, how does a post increment operator act in a return statement?

前端 未结 5 1185
忘了有多久
忘了有多久 2020-12-11 14:53

Given the following code, will ixAdd do what you\'d expect, i. e. return the value of ix before the increment, but increment the class member before leaving the function?

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 15:55

    The key part is that a post increment/decrement happens immediately after the expression is evaluated. Not only does it happen before the return occurs - it happens before any later expressions are evaluated. For instance, suppose you wrote:

    class myCounter {
        private int _ix = 1;
    
        public int ixAdd()
        {
            return _ix++ + giveMeZero();
        }
    
        public int giveMeZero()
        {
            System.out.println(_ix);
            return 0;
        }
    }
    

    That would print out the incremented result as well, because the increment happens before giveMeZero() is called.

提交回复
热议问题