uBASIC: wrong loop FOR/NEXT Edit

Sample script

   @title Test FOR/NEXT
   rem ------LOOP OK----------
   x = 5
   gosub "loop"
   rem -----LOOP NOT OK-------
   x = 0
   gosub "loop"
   print "-------------"
   print "Loop from", 1, "to", x
   for i = 1 to x
       print "value of i =", i
   next i

Output of script

   >>> -------------
   >>> Loop from 1 to 5
   >>> value of i = 1
   >>> value of i = 2
   >>> value of i = 3
   >>> value of i = 4
   >>> value of i = 5
   >>> -------------
   >>> Loop from 1 to 0
   >>> value of i = 1              <-- NOT OK

thanks you for CHDK!!!


What should happen in your opinion? I think "for i = 1 to 0" makes no sense. --Harvester 04:30, 2 June 2007 (UTC)
Actually, the body of the second 'for' should never be executed. But currently 'for' statement always evaluates his body at least once, even if the condition is false in the begining. uBasic has this bug 'by design'. So, it's quite hard to fix this (but it's possible, of course). --GrAnd 05:54, 2 June 2007 (UTC)

According to my experience with other languages, I was expecting the body of FOR not to be executed. The check to decide if closing the loop, it should be at the beginning of the loop (FOR) and not at the end (NEXT). For the moment I solved:

   if x < 1 then goto "label1"
   for i = 1 to x
       print "value of i =", i
   next i


All interpreted BASICs I know behave this way. That is because they parse the code line by line as they execute it. When they meet the FOR sentence, they don't know beforehand where the NEXT is, and thus can't jump to it. But when they reach the NEXT, they have already passed the FOR (and saved it into the stack), so they can check the end condition and go back to the FOR if it isn't met. I don't know much of uBASIC, either, but I have some experience with language interpreters, and I'd say it would be hard (and expensive in terms of execution speed) to fix this "bug".


Community content is available under CC-BY-SA unless otherwise noted.