Variation in FOR...NEXT behaviour

There's a very interesting discussion taking place over at the 'BASIC Programming Language' Facebook group, about the differences between different dialects in respect of the FOR...NEXT loop.

I was aware, of course, of the difference whereby some BASICs always execute the loop at least once (BBC BASIC is one) whereas others don't execute the body of the loop at all if the initial conditions are not met (e.g. FOR A = 5 TO 3).

But did you know that this code behaves differently according to the dialect:
10 A = 5
20 FOR A = 1 TO A + 5
30 PRINT A
40 NEXT A
In BBC BASIC this prints 1 to 6, whereas in Liberty BASIC for example it prints 1 to 10 !

Or this case:
10 T = 10
20 FOR A = 1 TO T
30 T = 5
40 PRINT A
50 NEXT A
In most BASICs this prints 1 to 10, but in a few (surprisingly including MS SmallBasic) it prints 1-5 !

Comments

  • Soruk
    edited January 28
    I was aware, of course, of the difference whereby some BASICs always execute the loop at least once (BBC BASIC is one) whereas others don't execute the body of the loop at all if the initial conditions are not met (e.g. FOR A = 5 TO 3).
    Neither the Sinclair Spectrum or Amstrad CPC executes the loop if the initial condition isn't met (as per your example above).
    10 A = 5
    20 FOR A = 1 TO A + 5
    30 PRINT A
    40 NEXT A
    
    In BBC BASIC this prints 1 to 6, whereas in Liberty BASIC for example it prints 1 to 10 !
    Matrix Brandy also prints 1 to 6, the Sinclair Spectrum BASIC and Locomotive BASIC on the Amstrad CPCs print 1 to 10.
    Or this case:
    10 T = 10
    20 FOR A = 1 TO T
    30 T = 5
    40 PRINT A
    50 NEXT A
    
    In most BASICs this prints 1 to 10, but in a few (surprisingly including MS SmallBasic) it prints 1-5 !
    In this instance, Matrix Brandy, the Spectrum and the Amstrad CPCs all print 1 to 10.

    I don't have any other flavours of BASIC that I have any familiarity with.
Sign In or Register to comment.