Why doesn't changing the pre to the post increment at the iteration part of a for loop make a difference?

Why does this

 int x = 2;
    for (int y =2; y>0;y--){
        System.out.println(x + " "+ y + " ");
        x++;
    }

prints the same as this?

 int x = 2;
        for (int y =2; y>0;--y){
            System.out.println(x + " "+ y + " ");
            x++;
        }

As far, as I understand a post-increment is first used "as it is" then incremented. Are pre-increment is first added and then used. Why this doesn't apply to the body of a for loop?


The loop is equivalent to:

int x = 2;
{
   int y = 2;
   while (y > 0)
   {
      System.out.println(x + " "+ y + " ");
      x++;
      y--; // or --y;
   }
}

As you can see from reading that code, it doesn't matter whether you use the post or pre decrement operator in the third section of the for loop.

More generally, any for loop of the form:

for (ForInit ; Expression ; ForUpdate)
    forLoopBody();

is exactly equivalent to the while loop:

{
    ForInit;
    while (Expression) {
        forLoopBody();
        ForUpdate;
    }
}

The for loop is more compact, and thus easier to parse for such a common idiom.


To visualize these things, expand the for loop to a while loop:

for (int i = 0; i < 5; ++i) {
    do_stuff(i);
}

Expands to:

int i = 0;
while (i < 5) {
    do_stuff(i);
    ++i;
}

Whether you do post-increment or pre-increment on the loop counter doesn't matter, because the result of the increment expression (either the value before or after the increment) isn't used within the same statement.


There's no difference in terms of performance, if that's your concern. It can only be used wrongly (and thus sensitive to errors) when you use it during the increment.

Consider:

for (int i = 0; i < 3;)
   System.out.print(++i + ".."); //prints 1..2..3


for (int i = 0; i < 3;)
   System.out.print(i++ + ".."); //prints 0..1..2

or

for (int i = 0; i++ < 3;)
   System.out.print(i + ".."); //prints 1..2..3


for (int i = 0; ++i < 3;)
   System.out.print(i + ".."); //prints 1..2

Interesting detail is however that the normal idiom is to use i++ in the increment expression of the for statement and that the Java compiler will compile it as if ++i is used.


++i and i++ makes a difference when used in combination with the assignment operator such as int num = i++ and int num = ++i or other expressions. In above FOR loop, there is only incrementing condition since it is not used in combination with any other expression, it does not make any difference. In this case it will only mean i = i + 1.