Search code examples
javaoperators

Pre/post increment/decrement and operator order confusion


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)  {
      --x;
      y=y-2; 
    }
    else { 
      x=x/2;
      b=b-x-1; 
    }
  }
  return x+y; 
} 

What is the purpose of b=y--? So, for example, x=5 and y=5 when we first go inside of while loop (while (b>0)) will b = 4 or 5? When I am running the code in my computer b is 5. And the return is 3. It is really unclear to me. Sorry if I am unclear in my question.


Solution

  • 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);
        }
    }