CAUTION: "Do" Be Careful!

(By: brucifer)


When you use a "Do-Loop", Bruce informs us:

"...watch out when the combination of end limit and step size approach the -32768 / +32767 boundary (for Ints) or the -2147483648 / +2147483647 boundary (for Int2s). If adding the step to the index causes the boundary to be crossed, the loop can be longer than expected (or infinite). See the examples below:

test  ( 32760, 32767, 1) @
test2 ( 32760, 32767, 1) @
test  (-32760,-32768,-1) @
test2 (-32760,-32768,-1) @
test2 ( 2147483645, 2147483647, 1) @
test2 (-2147483645,-2147483648,-1) @
test  ( 10000, 30000, 10000) @
test  (-10000,-30000,-10000) @
test2 ( 500 000 000,  2 000 000 000,  500 000 000) @
test2 (-500 000 000, -2 000 000 000, -500 000 000) @

Task test (Int a, Int b, Int c)
  Do n = a,b,c
    Display n,,
    If (sgn(n) != sgn(c))
      Display "UH-OH!"
      Return
    End if
  Loop
  Display

Task test2 (Int2 a, Int2 b, Int2 c)
  Do n = a,b,c
    Display n,,
    If (sgn(n) != sgn(c))
      Display "UH-OH!"
      Return
    End if
  Loop
  Display            
As the third and fourth examples illustrate, you can use Int2s to avoid the -32767 / +32768 boundary, but all this does is push it out to the -2^31 / +2^31-1 boundary. It makes it easier to spot when the loop limit is near +/- 2^15 or +/- 2^31 (Fortunately, when I encountered this I had a loop limit of 32767 and a step of 1, so I was able to figure out why I had an infinite loop without too much trouble). However, note that in the last four examples, the loop limit and step size don't suggest why the loop doesn't terminate when expected."



  [ Webmaster | FAQ's | Home Page | Contact Us ]