0

The difference between for(i=0;i<5;i++) and for(i=0;i<5;++i)?

12th Aug 2017, 11:45 AM
Shaik Abdul kalam Azad
Shaik Abdul kalam Azad - avatar
6 Answers
+ 6
It's the difference between post-increment and pre-increment. In this case, it doesn't make much of a difference to the semantics of your code. Both loops with execute in exactly the same way. But the distinction is this: "i++" will create a temporary copy of "i", increment the original "i", and then return the copy. Since you don't do anything with the copy, it's unnecessary computation for no benefit (note that most compilers will optimize this out, though, so you don't need to worry too much). "++i", on the other hand, just increments "i" and then returns the new value of "i", with no copying taking place. When you don't use the original value of "i" (and you don't in this context), you should prefer "++i".
12th Aug 2017, 11:54 AM
Squidy
Squidy - avatar
+ 5
Squidy nailed it. In other words it (++i) is faster (*if the compiler hasnt optimized as per Squidys perfect answer)
12th Aug 2017, 11:55 AM
jay
jay - avatar
+ 3
No @Shaik, the whole statement in the third part of the for loop is done before the condition (after at least one looping) if you do if(I++) or if(++I), here it will have an impact
12th Aug 2017, 1:15 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
squidy, do u mean that in i++ at first condition is verified then program is excuted later increment where as in ++i at first increment then condition is verified later program is excuted,( here program mean loop)
12th Aug 2017, 12:02 PM
Shaik Abdul kalam Azad
Shaik Abdul kalam Azad - avatar