[Coco] Bug in FOR NEXT ?

William Astle lost at l-w.ca
Thu Jun 1 11:25:09 EDT 2006


Rod Barnhart wrote:
> It makes perfect sense that the Basic for-next works the same as the C for
> does, but in all my years of programming, I don't think I've ever been
> taught or come across that. I guess you can teach an old programmer new
> tricks.

It's not surprising that you didn't come across it. For the most part,
you wouldn't be using the exit value of the iterator in a for loop.

Now if you really want something to blow your mind, try this. (It
possibly is CoCo Basic specific):

FOR X=1 TO 5
FOR Y=1 TO 5
PRINT X;";";Y
IF Y=X THEN NEXT X ELSE NEXT Y:NEXT X
PRINT X;";";Y

That should print the following:

 1; 1
 2; 1
 2; 2
 3; 1
 3; 2
 3; 3
 4; 1
 4; 2
 4; 3
 4; 4
 5; 1
 5; 2
 5; 3
 5; 4
 5; 5
 6; 5

What happens here is that when the IF test is true and the NEXT X
executes, the system looks back through the stack, finds the FOR loop
for X, determines it matches, and pretends that's the current location
on the stack. The end result is that the FOR Y loop just disappears.

You can get even more wacky results by combining FOR and GOSUB. For
example, starting a FOR loop in a subroutine but executing a RETURN in
the middle of the loop will, in fact, eliminate the loop from the stack.
Likewise, if you execute a GOSUB in the middle of a FOR loop and then
execute a bare "NEXT" in the subroutine, the subroutine disappears and
execution resumes at the beginning of the FOR loop.

Gotta love stack effects.

-- 
William Astle
finger lost at l-w.net for further information

Geek Code V3.12: GCS/M/S d- s+:+ !a C++ UL++++$ P++ L+++ !E W++ !N w---
!D !M PS PE V-- Y+ PGP t+@ 5++ X !R tv+@ b+++@ !DI D? G e++ h+ y?



More information about the Coco mailing list