+ 2

Incrementation and the for loop

Can someone explain when exactly incrementation of the "for" loop variable occurs in this code?: for (int i = 0; i < 3; ++i) { cout << i; } Apparently the output of this code is "012", but I thought it would be "123" as I thought that the "++" incremental being before the "i" meant it would increment immediately, before "cout". The actual output for this code is the same as if it read "i++", so what would "++i" be useful for in a "for" loop?

16th Mar 2017, 6:56 PM
Daniel Davis
Daniel Davis - avatar
6 Respostas
+ 16
this thread is really helpful for undertanding prefix and postfix...thank you
18th Mar 2017, 3:42 PM
‎‏‎‏‎Joe
‎‏‎‏‎Joe - avatar
+ 5
++i would change something if it where like that : for(int i=0;++i<3;) but it is better to use a while or do while loop in this case
16th Mar 2017, 7:14 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 5
@Navaneeth Kz, I agree on the fact that it is the programmers choice. Have a nice day too :)
16th Mar 2017, 7:35 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 4
@Navaneeth Kz, I am not really a beginner (not a pro though) and I do not think that for loops are better. Each loop has its purpose and should be use in this way. Break should be avoided (even if they are useful when they avoid a lot of if statements).
16th Mar 2017, 7:28 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 3
@Baptiste E. Prunier I agree, a "while" loop would be preferential in that case.
16th Mar 2017, 7:21 PM
Daniel Davis
Daniel Davis - avatar
+ 2
@Navaneeth Kz Thank you for the breakdown of the "for" loop's execution timing. So using "++i" is really no different than using "i++" in the "for" loop. I'm glad to have confirmation that I really do understand the difference in "i++" and "++i". I just didn't really understand when the incrementation would occur in a "for" loop. Thanks for the response!
16th Mar 2017, 7:25 PM
Daniel Davis
Daniel Davis - avatar