Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 783
andandandand Avatar asked Dec 16 '09 22:12

andandandand


People also ask

How does pre increment and Post increment work in for loop?

Pre increment directly returns the incremented value, but post increments need to copy the value in a temporary variable, increment the original and then returns the previous made copy.

Does pre increment matter in for loop?

It makes no difference in a for loop. The difference between ++i and i++ is when you are trying to use the value of i in the same expression you are incrementing it.

What is the difference between pre increment and post increment?

Pre-increment (++i) − Before assigning the value to the variable, the value is incremented by one. Post-increment (i++) − After assigning the value to the variable, the value is incremented.

Is i ++ same as ++ i in for loop?

Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated. To answer the actual question, however, they're essentially identical within the context of typical for loop usage.


1 Answers

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.

like image 174
Paul Wagland Avatar answered Sep 20 '22 19:09

Paul Wagland