Jumping out of a nested FOR loop gives unexpected results

From Liberty BASIC Family
Jump to navigation Jump to search

Description

Jumping out of a FOR loop is bad practice because it causes a memory leak, but in the case of nested loops it can also give strange results. Specifically, the loop variable seems not to be reset to the initial value when the FOR is executed again.

Example code to demonstrate the bug.

    for y = 1 to 3
      for x = 1 to 5
        if x = 4 then goto [skip]
        print x, y
      next x
    [skip]
    next y

The expected output from this program is:

1             1
2             1
3             1
1             2
2             2
3             2
1             3
2             3
3             3

but the actual output is:

1             1
2             1
3             1
5             1
1             2
2             2
3             2
5             2
1             3
2             3
3             3
5             3

One would not expect x ever to have the value 5!

Example code to work around the bug.

Use EXIT FOR. It is explicitely stated in a help file, "FOR..NEXT" \ Exiting a loop prematurely:

GOTO should not be used to exit a FOR/NEXTloop. "EXIT FOR" will correctly exit the loop before it would have terminated normally.

    for y = 1 to 3
      for x = 1 to 5
        if x = 4 then exit for
        print x, y
      next x
    next y

Related bugs

You can get same behavoiour with other kinds of loops (DO / LOOP, WHILE / WEND).

EXIT DO, EXIT WHILE saves the day, as well.

Other versions of Liberty BASIC

This 'bug' does not exist in Liberty BASIC 5 or in Run BASIC. You can jump out of a FOR/NEXT loop in those versions without issues.