Pre/post increment/decrement and operator order confusion

前端 未结 4 1403
天命终不由人
天命终不由人 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: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.

提交回复
热议问题