Tags C & C++

I stumble on the following problem a lot:

Consider iterating over an array. I like to use an unsigned value for the array index - it's cleaner. size_t, for instance, is unsigned. The dogmatic iteration is:

for (size_t i = 0; i < SIZE; ++i)
  ...

But sometimes, a poor 'n innocent soul wants to iterate over the array backwards, and writes this code:

for (size_t i = SIZE - 1; i >= 0; --i)
  ...

Noticed the bug ?

Not yet ? Think what happens on the last iteration. i is 0, we end the iteration, decrease it and test against 0. You'd expect this test to fail and the loop to exit, right ? Wrong. i is likely to be 4294967295 (on 32-bit machines...), not 0, since size_t is unsigned !

So, there's no clean way to do this iteration, it seems (clean = without index arithmetic). In C++ you should really use iterators though :-)


Comments

comments powered by Disqus