You might think of a for loop
for (<decl-init> ; <condition> ; <post-adjust>) <body>
as the gross equivalent of this while :
<decl-init>; while (condition) { <body>; <post-adjust>; }
The biggest difference between for and the above is the scope of the variables declared in the <decl-init> block, but this is not important for the analysis below.
Rewriting both loops as a while gives you the following:
int i = v.size() - 1; while ( i >= 0 ) { <body>; i--; }
against.
int i = v.size(); while (i--) { <body>; }
As you can see, the only difference is that i decreases before the iteration is entered, and the condition starts with i more by 1 than in the first cycle. These two settings βcancel each other outβ, making your loops technically equivalent. Aesthetics is a completely different matter: conditions with side effects are more difficult to understand than βpureβ ones, so the first cycle is more readable.
dasblinkenlight
source share