BASIC stamp manual v2.2

5: BASIC Stamp Command Reference – FOR...NEXT
BASIC Stamp Syntax and Reference Manual 2.2 www.parallax.com Page 195
number). If you add 1 to 65535, you get 0 as the 16-bit register rolls over
(like a car’s odometer does when you exceed the maximum mileage it can
display). Similarly, if you subtract 1 from 0, you'll get 65535 as the 16-bit
register rolls under (a rollover in the opposite direction).
If you write a FOR...NEXT loop who's StepValue would cause Counter to go
past 65535, this rollover may cause the loop to execute more times than
you expect. Try the following example:
reps VAR Word ' counter for the loop
FOR reps = 0 TO 65535 STEP 3000 ' each loop add 3000
DEBUG DEC ? reps ' show reps in Debug window
NEXT
The value of reps increases by 3000 each trip through the loop. As it
approaches the EndValue, an interesting thing happens; reps is: 57000,
60000, 63000, 464, 3464... It passes the EndValue, rolls over and keeps
going. That’s because the result of the calculation 63000 + 3000 exceeds the
maximum capacity of a 16-bit number and then rolls over to 464. When
the result of 464 is tested against the range (“Is Reps > 0 and is Reps <
65535?”) it passes the test and the loop continues.
A similar symptom can be seen in a program who's EndValue is mistakenly
set higher than what the counter variable can hold. The example below
uses a byte-sized variable, but the EndValue is set to a number greater than
what will fit in a byte:
SYMBOL reps = B2 ' counter for the loop
FOR reps = 0 TO 300 ' each loop add 1
DEBUG reps ' show reps in Debug window
NEXT
-- or --
reps VAR Byte ' counter for the loop
FOR reps = 0 TO 300 ' each loop add 1
DEBUG DEC ? reps ' show reps in Debug window
NEXT
Here, reps is a byte variable; which can only hold the number range 0 to
255. The EndValue is set to 300, however; greater than 255. This code will
loop endlessly because when reps is 255 and the FOR…NEXT loop adds 1,
NOTE: For BS1's, change line 1 to
SYMBOL reps = W0
and line 3 to
DEBUG reps
1
1
All
2