Set the WABAC machine, Sherman. This question is about BASIC in general, and Microsoft's BASIC-80 in particular. Old school basic. With line numbers.
How do (or, rather, did) old-school BASIC interpreters handle FOR...NEXT loops when the loop body was not executed, and the NEXT statement appeared out of order?
An out-of-order NEXT statement from the before time:
Here's a subroutine from the game Awari out of David H. Ahl's "101 Basic Computer Games":
200 K=M:GOSUB 600
205 E=0:IF K>6 THEN K=K-7
210 C=C+1:IF C<9 THEN F(N)=F(N)*6+K
215 FOR I=0 TO 5:IF B(I)<>0 THEN 230
220 NEXT I
225 RETURN
230 FOR I=7 TO 12:IF B(I)<>0 THEN E=1:RETURN
235 GOTO 220
and here it is with everything except the flow control redacted:
200 GOSUB 600
215 FOR I=0 TO 5:IF ... THEN 230
220 NEXT I
225 RETURN
230 FOR I=7 TO 12:IF ... THEN RETURN
235 GOTO 220
Does that bring back not-so-fond memories? Can you hear Dijkstra rolling over in his grave?
Here are the interesting part of what's happening in this fragment:
- The second FOR loop, since it uses the same loop variable, replaces the first FOR loop
- The two FOR loops share the same NEXT statement
- The second FOR loop's NEXT statement comes before it, in source order, but after it, in execution order
You might suppose, then, that the interpreter, having started a FOR loop, simply runs statements until it happens across the NEXT loop. The order of the statement in the source does not matter in this case. But let's see what the basic80 manual has to say about FOR loops:
The basic-80 manual says "moo..."
The body of the loop is skipped if the initial value of the loop times the sign of the step exceeds the final value times the singsign of the step.
So, the loop body can be skipped entirely.
We have evidence, in the form of published programs, that at least some versions of BASIC were dynamically locating their NEXT statements. This is easy enough to do when the loop body is being executed. However, in the case where the body of the FOR statement should be skipped, as BASIC-80 permits, how did BASIC locate the NEXT statement, given that it might be before the FOR statement in source order?
- Did the version of BASIC used in "101 Basic Computer Games" always execute the loop body at least once?
- Did BASIC-80 require a FOR loop's NEXT statement to occur after the FOR statement, in source order?
PS: Yes, I'm writing a BASIC interpreter for old school BASIC. It's a sickness.