-> Because a FOR loop has 'local' (private) variables - the 'step' value
-> and the 'limit' value - and it is conventional to store local
-> variables on a stack. These local variables must be independent of
-> all other variables, including the local variables of an outer or
-> inner FOR loop, and there can be an arbitrary number of them
-> (especially if you use reentrant code).
-> If instead of a stack you use a static memory area to hold the 'step'
-> and 'limit' values, that will impose a maximum depth of nesting of
-> FOR..NEXT loops, which is undesirable.
-> > BTW: nested loops with the same variable are illegal in TI Basics -
-> > which is as it should be.
-> That's probably OK, so long as this kind of construction is allowed:
-> FOR i = 1 TO 5
-> CALL test
-> NEXT i
-> END
-> SUB test
-> FOR i = 1 TO 5
-> PRINT i
-> NEXT
-> END SUB
-> If it rejects that (or the equivalent in your favorite syntax) as
-> 'nested loops with same control variable' then it would impose
-> unacceptable constraints on the use of 'reusable code'. In other
-> words you ought not to have to care what control variable may be used
-> inside a subroutine when writing code which calls it.
-> Richard.
In this case, it's not the FOR loop that has its own local variables,
it's the SUB. The "i" within the SUB is a different variable than the
"i" outside it.
If you use a GOSUB instead:
FOR i = 1 TO 5
GOSUB test
NEXT i
test:
FOR i = 1 TO 5
PRINT i
NEXT i
RETURN
in many BASICs you will run into stack problems. In this case, the "i"
is a global variable, so when the loop inside the subroutine is set up,
it wipes out the outside loop, including (probably) the GOSUB
information. The RETURN instruction then causes a "RETURN without GOSUB
error".
dow


|