3 ms·
I don't like C for loops, either, but this can happen with other types of for loops, either. E.g. in Pascal: for i := 0 to len-1 do begin ... end This is co
by rbehrends 12y ago
I don't like C for loops, either, but this can happen with other types of for loops, either. E.g. in Pascal:
for i := 0 to len-1 do begin ... end
This is counting up, not counting down, and len-1 is still going to be either 2^k-1 or result in an error when you're using unsigned integers.
While loops also don't fix it (not to mention that they have their own problem, such as forgetting or misplacing the iteration step). The primary issue is that len-1 is underflowing. Yes, you can avoid calculating len-1, but by that token, no error is ever a problem, because they can all be avoided with enough diligence and foresight. In that universe, Heartbleed never happened and the Ariane 5 never blew up. It is, however, not the world we live in.
- detrino 12y agoThat's a representation problem. C/C++ use half open ranges and have no problems with unsigned integers. This is also a non-issue in C++ as you have iterators and counting loops are easy to abstract away using counting iterators or <algorithm> style functions.