4 ms·
The common counting down problem he's referring to is where an unsigned iterator can never be <0, so it introduces an infinite loop. Setting a found boolean doe
by pmikesell 11y ago
The common counting down problem he's referring to is where an unsigned iterator can never be <0, so it introduces an infinite loop. Setting a found boolean does nothing to alleviate that situation.
- Zikes 11y agoAdditionally, "found" may never be true if you don't find what you're looking for. Instead, you would want a boolean for whether or not you've searched all array elements.
- notacoward 11y agoTrue, 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.