EXIT FOR

Anything QL Software or Programming Related.
Post Reply
User avatar
dilwyn
Mr QL
Posts: 3169
Joined: Wed Dec 01, 2010 10:39 pm

EXIT FOR

Post by dilwyn »

I've just spent a while debugging a BASIC program which didn't give the expected results for someone.

Turned out to be an issue concerning FOR loops which, while documented in places like the Jan Jones guide, is easy to forget about.

The program concerned had (I think) been converted from a BASIC on another computer. Here's a very simplified version of where the program was going wrong. In itself, it's a pointless nonsense, but more clearly explains where the original spaghetti code was going wrong (other BASICs use FOR/NEXT, not FOR/END FOR):

Code: Select all

100 CLS
110 FOR a = 1 TO 10
120   PRINT a
130   IF RND(1 TO 5) = 1 THEN EXIT a
140 NEXT a
150 PRINT'Line 150'
If line 130 is true, the EXIT statement is executed. But line 150 is never executed.

It's as simple as an EXIT from a FOR statement searches for the corresponding END FOR statement, and if not found the program just stops as normal with no error code, giving little clue what's happening. You might expect it to go to the line after the NEXT statement, but if you are using the EXIT statement there has to be an END FOR a instead of the NEXT a for it to work as you'd want! In the case of the program listing concerned, all the FOR/NEXT loops had been converted as FOR/NEXT instead of FOR/END FOR.

In short, the program concerned was parsing words by looking through an array list and exiting the parsing loop when a match was found, but the program just stopped with no error when a match was found in the list. Took a while to get my brain sufficiently in gear to resolve the issue!


Post Reply