For Loop Gotchas

Be careful when writing loops with unsigned variables. The compiler’s idea of an end condition might not match yours.

When working on a program to produce fractal laser-engraver art, I stumbled across a strange problem. I could call a function to draw a fractal at levels 0 through 6, all of which worked fine, whether individually or called in a for loop.

When I went to draw them in reverse order, however, the program crashed — and it didn’t make sense as to why. The code in question was something like:

dim as ulongint x
for x=6 to 0 step -1
drawObject(x)
next x

This worked fine forwards (for x=0 to 6) but crashed somewhere around level 2 when run in reverse — even though all levels worked great individually.

I eventually figured out that the bug was due to the variable in the for loop. Instead of iterating from 6 down to zero and then stopping, for loops (in FreeBasic as well as C) blindly decrement the variable and then check the end condition.

So, in C, a line which reads

for(uint8_t x=6;x>=0;x--){doTheThing(x);}

will never return. It will get down to zero, decrement and wrap back to all-ones. Since this is a value greater than zero, it will continue.

In the case of the fractal image, I had unknowingly asked it to compute an 18.4667-quintillion-level Koch curve. This figure would have four-to-the-18.4667-quintillionth-power segments.

No wonder it crashed!

This entry was posted in BASIC, C, Coding, Fractals. Bookmark the permalink.

Leave a Reply