+ 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?
6 Respuestas
+ 16
this thread is really helpful for undertanding prefix and postfix...thank you
+ 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
+ 5
@Navaneeth Kz, I agree on the fact that it is the programmers choice.
Have a nice day too :)
+ 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).
+ 3
@Baptiste E. Prunier
I agree, a "while" loop would be preferential in that case.
+ 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!