User Tools

Site Tools


alternative_20for_20next_20behaviour

Alternative FOR NEXT behaviour

by Richard Russell, July 2007

Although the FORNEXT loop is fundamental to all versions of BASIC, dialects differ in its detailed implementation. In BBC BASIC FOR…NEXT loops have the following properties:

  • The body of the loop is always executed at least once, irrespective of the values specified in the FOR statement.
  • On exit from the loop the loop variable has a value greater than (for a positive STEP) the TO value specified in the FOR statement, i.e. one more STEP has taken place.

The following examples illustrate this behaviour:

        FOR i% = 1 TO 0
          PRINT i%
        NEXT i%
        FOR i% = 1 TO 10
        NEXT i%
        PRINT i%

The first loop prints 1, even though the 'finish' value is less than the 'start' value.

The second loop prints 11, which is one more than the 'finish' value.

On occasion you may wish to emulate the behaviour of a different BASIC dialect, for example when porting a program to BBC BASIC. One convenient way of doing that is to use the EXIT FOR statement.

Some BASIC dialects do not execute the FOR loop at all if the initial conditions aren't met, i.e. the 'finish' value is less than the 'start' value (with a positive STEP). To emulate that behaviour use code similar to the following:

        FOR loopvar = start TO finish
          IF loopvar > finish THEN EXIT FOR
          REM Body of loop here
        NEXT loopvar

Some BASIC dialects exit the loop with the loop variable equal to the 'finish' value. To emulate that behaviour use code similar to the following:

        FOR loopvar = start TO finish
          REM Body of loop here
          IF loopvar >= finish THEN EXIT FOR
        NEXT loopvar

Of course you can combine both behaviours if you wish:

        FOR loopvar = start TO finish
          IF loopvar > finish THEN EXIT FOR
          REM Body of loop here
          IF loopvar >= finish THEN EXIT FOR
        NEXT loopvar

In all cases if the STEP is negative you need to reverse the comparisons:

        FOR loopvar = start TO finish STEP -delta
          IF loopvar < finish THEN EXIT FOR
          REM Body of loop here
          IF loopvar <= finish THEN EXIT FOR
        NEXT loopvar
This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
alternative_20for_20next_20behaviour.txt · Last modified: 2024/01/05 00:22 by 127.0.0.1