3 ms·
True, that part's still a potential problem. I often avoid it with something like this (which I believe is more clear anyway). i = arraylength; while (i
by notacoward 11y ago
True, that part's still a potential problem. I often avoid it with something like this (which I believe is more clear anyway).
i = arraylength;
while (i-- > 0)
In other cases it really does make more sense to count up. Another unconsidered possibility is that the "found" case might actually return from an iterator function, so you can put the "not found" case after the loop regardless of which way you're counting.
The "counting down can cause an infinite loop" problem does exist, but I've also seen cases where counting up can fail too (e.g. index incremented twice within a loop either accidentally or deliberately), or where confusion of whether to use "i" or "i-1" caused bugs. It's probably even easier for a static analyzer to catch a counting-down bug than a counting-up bug, so I'm not really sure that a preference for counting up is all that helpful.