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

andandandand picture andandandand · Dec 16, 2009 · Viewed 19.1k times · Source

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?

Answer

Paul Wagland picture Paul Wagland · Dec 16, 2009

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.