For..Next

russbow

Senior Member
Is it permissible to exit a for / next loop before it has completed?
For instance, a condition could be met ( if...then ) halfway through the loop count. Could I use a goto in this case and leave the for/next in limbo, or should I use a gosub so that I return to the loop to clean up the dregs. What if I want to re-run the loop later in the programme?

I just love this, everytime you crack a problem, another one arises.

Regards,

Russ
 

Janne

Senior Member
I think you should use the "exit" command that is reserved just for this purpose.


example:
Code:
for b0 = 1 to 90

IF b0=50 THEN EXIT

next b0
this would exit the for loop when b0 reached 50
 
Last edited:

BeanieBots

Moderator
Wise to be cautious as many variants of BASIC get very upset if you exit loops indiscriminately.

To the best of my knowledge there is no problem leaving a for/next loop in PICAXE BASIC. I have several programs which do just that and they have never indicated a problem.

Have a look at page 45 of the manual and you will find the "exit" command.
Probably a more graceful way of leaving rather than using a goto.
 

hippy

Ex-Staff (retired)
In the case of PICAXE Basic it is entirely safe to GOTO out of a FOR-NEXT loop, even jump into them if used with care but that is not good programming practice.

FOR var = start TO end STEP +/- step
statements
NEXT

is equivalent to -

var = start
Do
statements
var = var +/- step
Loop While var >= start And var <= end

That is also why PICAXE FOR-NEXT loops will always execute at least once, even when 'end' is less than 'start', which is not always the case with other programming language implementations of FOR-NEXT.
 
Last edited:
Top