Go to the Next or Previous section, the Detailed Contents, or the Amiga E Encyclopedia.


10.5.3 EXIT statement

As noted above, you can use the JUMP statement and labelling to break out of a loop prematurely. However, a much nicer mechanism exists for WHILE and FOR loops: the EXIT statement. This statement will terminate the closest one of these loops (of which it is part) if the supplied expression evaluates to true (i.e., a non-zero value). Any loop using EXIT can be re-written without it, but sometimes at the expense of readability.

The following fragments of code are equivalent:

  FOR x:=1 TO 10
    y:=f(x)
  EXIT y=-1
    WriteF('x=\d, f(x)=\d\n', x, y)
  ENDFOR

  FOR x:=1 TO 10
    y:=f(x)
    IF y=-1 THEN JUMP end
    WriteF('x=\d, f(x)=\d\n', x, y)
  ENDFOR
end:

This example shows a situation which is arguably more readable using something like EXIT. It can be rewritten using a WHILE loop, as below, but the code is a bit less clear.

  going:=TRUE
  x:=1
  WHILE going AND (x<=10)
    y:=f(x)
    IF y=-1
      going:=FALSE
    ELSE
      WriteF('x=\d, f(x)=\d\n', x, y)
      INC x
    ENDIF
  ENDWHILE


Go to the Next or Previous section, the Detailed Contents, or the Amiga E Encyclopedia.