c/c++ annoyance - unsigned iteration

July 18th, 2004 at 10:42 pm

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 :-)

Related posts:

  1. complying with -Wall -pedantic -ansi
  2. Initializing an array in constant time
  3. Allocating multi-dimensional arrays in C++
  4. a cool algorithm for counting ones in a bitstring

Leave a Reply

To post code with preserved formatting, enclose it in `backticks` (even multiple lines)