Monday, 9 December 2013

Looping back and forth, unsigned ranges.

I just saw this post about unsigned loop problems on Eli Blendersky's blog:

In it he tells a tale of woe with unsigned values not being easy to test when doing negative for loops, but one trick that I've used numerous times for checking ranges applies here too. I've marked the changes.

Positive loop:
for (size_t i = 0; i < SIZE; ++i)

Negative loop:
for (size_t i = SIZE-1; i < SIZE; --i)

What? Ah, unsigned types are unsigned, so -1 is really big. Cool. Go use this in your code. Ranges are handled the same way:

if ( (unsigned_value-RANGE_MIN) < (RANGE_MAX-RANGE_MIN) )

No comments: