Pre/post increment/decrement and operator order confusion

前端 未结 4 1398
天命终不由人
天命终不由人 2021-01-15 07:45

I was going through some exercises but I am confused in this one:

public static int f (int x, int y) {
  int b=y--;
  while (b>0) {
    if (x%2!=0)  {
            


        
相关标签:
4条回答
  • 2021-01-15 08:33

    int b=y--; first assignes b=y and then decrements y (y--).

    Also take a look at the prefix/postfix unary increment operator.

    This example (taken from the linked page) demonstrates it:

    class PrePostDemo {
        public static void main(String[] args){
            int i = 3;
            i++;
            // prints 4
            System.out.println(i);
            ++i;               
            // prints 5
            System.out.println(i);
            // prints 6
            System.out.println(++i);
            // prints 6
            System.out.println(i++);
            // prints 7
            System.out.println(i);
        }
    }
    
    0 讨论(0)
  • 2021-01-15 08:37

    The difference between a post-increment/decrement and a pre-increment/decrement is in the evaluation of the expression.

    The pre-increment and pre-decrement operators increment (or decrement) their operand by 1, and the value of the expression is the resulting incremented (or decremented) value. In contrast, the post-increment and post-decrement operators increase (or decrease) the value of their operand by 1, but the value of the expression is the operand's original value prior to the increment (or decrement) operation.

    In other words:

    int a = 5;
    int b;
    b = --a;    // the value of the expression --a is a-1. b is now 4, as is a.
    b = a--;    // the value of the expression a-- is a. b is still 4, but a is 3.
    

    Remember that a program must evaluate expressions to do everything. Everything is an expression, even just a casual mention of a variable. All of the following are expressions:

    • a
    • a-1
    • --a && ++a
    • System.out.println(a)

    Of course, in the evaluation of expressions, operator precedence dictates the value of an expression just as the PEMDAS you learned in grade school. Some operators, such as increment/decrement, have side effects, which is of course great fun, and one of the reasons why functional programming was created.

    0 讨论(0)
  • 2021-01-15 08:42

    I believe b would equal 5 entering the loop because

    b=y--;
    

    When the "--" is behind the variable it decrements it after the action.

    0 讨论(0)
  • 2021-01-15 08:44

    It's poor coding, as it can confuse new programmers.

    The function, assuming it is passing by value, like in the example above (as opposed to passing by reference) takes a copy of y, decrements it, and assigns it to b. It does not alter the argument passed to the function when it was called.

    0 讨论(0)
提交回复
热议问题