Tuesday, October 14, 2014

i++ vs ++i (difference between postfix and prefix increment)

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand.

You know that both i++ and ++i increment i value by one. However, there is still significant difference between them:
  • ++i (prefix increment) - increments the value and then returns it.
  • i++ (postfix increment) - returns the value and then increments it.

    int i = 0;
    int n = i++
    System.out.println(n)  // output: 0
    System.out.println(i)  // output: 1
    ...
    i = 0;
    n = ++i;
    System.out.println(n)  // output: 1
    System.out.println(i)  // output: 1

Which one is better to use?

There is no difference when you use ++i or i++ on a line on its own (or in a for loops).

De facto i++ (postfix increment) is preferred, cause it's more readable and clear for understanding:

j = i++
equals to
j = i
i = i + 1
Treated like: "Save the current value and then increment it by 1"

in comparison:
j = ++i
which equals
i = i + 1
j = i
Sounds like: "Increment the current value by 1 and then assign it"


Which one is more efficient?

i++ :
  • create temporary copy of i
  • increment i
  • return temporary copy of i
++i :
  • increment i
  • return i
So, ++i is more efficient. However the temporary copy cost is non negligible. 
Better to prefer readability (i++) against an extra optimization.

Practice


    int i = 10;
    int n = i++%5   // result: i=10 n=0 
    ...
    int i = 10;
    int n = ++i%5;  // result: i=11 n=1
It's equivavalent to: 

    int i = 10;
    int n = i % 5   // result: i=10 n=0 
    i = i + 1;
    ...
    int i = 10;
    i = i + 1;
    int n = i % 5;  // result: i=11 n=1


No comments:

Post a Comment