Hi,
Often, I try to minimise the number of variables used in my code, particularly Subroutines and General Purpose code, because PICaxe Basic doesn't support "Local" variables. So I was recently looking to re-use the variables within a For ... Next loop.
I suspected that it would be legitimate to re-use the starting value and indeed the following code works as expected. Of course, changing the loop variable (accidentally) within the loop is a well-known "gotcha", but is "permitted" and occasionally useful (but arguably, poor programming) and just used here for demonstration.
But then I wondered about b2; is the loop "set up" at the start and b2 could then be re-used for another purpose? I suspected not, but tried this code in the simulator (PE5 and PE6):
Sadly, a "real" PICaxe doesn't behave the same way, so I haven't found the "spare" byte variable that I was looking for.
Cheers, Alan.
Often, I try to minimise the number of variables used in my code, particularly Subroutines and General Purpose code, because PICaxe Basic doesn't support "Local" variables. So I was recently looking to re-use the variables within a For ... Next loop.
I suspected that it would be legitimate to re-use the starting value and indeed the following code works as expected. Of course, changing the loop variable (accidentally) within the loop is a well-known "gotcha", but is "permitted" and occasionally useful (but arguably, poor programming) and just used here for demonstration.
Code:
b1 = 0
b2 = 20
for b1 = b1 to b2
sertxd (#b1," ")
inc b1
next
; SIMULATOR RESULT = 0 2 4 6 8 10 12 14 16 18 20
Code:
b1 = 0
b2 = 20
for b1 = b1 to b2
sertxd (#b2," ")
dec b2
next
; SIMULATOR RESULT = 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Cheers, Alan.