I thought that i know the concept of pre fix n post fix operators but I got confused once i saw ++i written in a for loop and working exactly the same way as i++. Please clarify ,how it behaves in the for loop
Originally posted by itisha jain: I thought that i know the concept of pre fix n post fix operators but I got confused once i saw ++i written in a for loop and working exactly the same way as i++. Please clarify ,how it behaves in the for loop
It works the same as anywhere else. The value of the i++ expression is not used; only its effects.
Unrolling the logic of that loop, we get the following:
int i = 0; if (i < 3) System.out.println(i); // 0 i++; // this expression evaluates to 0, but i is incremented to 1 if (i < 3) System.out.println(i); // 1 i++; // evaluates to 1; i is incremented to 2 if (i < 3) System.out.println(i); // 2 i++; // evaluates to 2; i is incremented to 3 if (i < 3) // it isn't, so the loop breaks
Hello Itisha, As far as I Think there is no difference in post-increment and pre-increment or post-decrement and pre-decrement if this statement is all alone, ie. not combined with any kind of assignment.
In case there is assignment with these operators the result might be different
hope this will help you
Regards<br />Sandy<br />[SCJP 5.0 - 75%]<br />[SCWCD 1.4 - 85%]<br />------------------<br />Tiger, Tiger burning bright,<br />Like a geek who works all night,<br />What new-fangled bit or byte,<br />Could ease the hacker's weary plight?
The ++i idiom may be a holdover from early C programming days.
As we all know, i++ "returns" the value of i BEFORE the increment, while ++i has the NEW value of i. In pseudo-assembly, i++ might look like this:
Whereas ++i can remove the use of registerB to hold the non-incremented value of i:
In both cases, the expression's value is left in registerA, ready to be assigned to a new variable, passed to a function, etc.
Soon, however, compilers became smart enough to recognize situations where the value of the i++ expression was being ignored, so they didn't bother saving the original value, thus making i++ just as efficient as ++i.
However, some programmers got into the habit of always using ++i and found no reason to stop. You never know, after your current Java programming job, you might start working with a new language that doesn't have the optimization, and a habit of using "++i" will serve you well.
And lastly, if you're reading code out loud, it's easier to say, "increment i," when you see ++i than when you see i++. [ October 04, 2005: Message edited by: Ryan McGuire ]