EXIT statement

Purpose

Transfer program execution out of a block structure.

Syntax

EXIT [FOR | FUNCTION | IF | DO | LOOP | MACRO | SELECT | SUB | TRY]

EXIT [, EXIT] [, ...] [, ITERATE]

Remarks

The EXIT statement lets you leave a structure prematurely.  Using EXIT by itself will leave the most recently executed structure.  For example:

FOR ix = 1 TO 10

  DO UNTIL x > 10

    ...

    EXIT  ' will exit from the DO LOOP

  LOOP

NEXT
 

EXIT option

Structure exited

FOR

FOR/NEXT loop

FUNCTION

FUNCTION/END FUNCTION function

IF

IF/END  IF block (see notes below)

DO or LOOP

DO/LOOP or WHILE/WEND loop

MACRO

MACRO/END MACRO block

SELECT

SELECT statement

SUB

SUB/END SUB procedure

TRY

TRY/END TRY block

If you want to exit a structure other than the one most recently executed, you must include that type of structure as part of the EXIT statement, as follows:

FOR ix = 1 TO 10

  DO UNTIL x > 10

    ...

    EXIT FOR  ' will exit DO and FOR NEXT loop

  LOOP

NEXT

Using EXIT is preferred over using GOTO.

You can exit nested loops by using multiple EXIT statements without the loop type, and separated by commas:

DO

  DO

    EXIT, EXIT  ' exit both loops

  LOOP

LOOP

You can also exit one loop and immediately iterate another:

FOR x = 1 TO 10

  DO

    EXIT, ITERATE

  LOOP

  ' never gets here

NEXT

If you EXIT the PBMAIN or WINMAIN function, your program will stop running.

Care should be exercised when constructing exits within a nested IF/THEN block.  For example:

IF x& THEN

  IF y& THEN

    {statements1}

    EXIT IF

    {statements2}

  END IF

  {statements3}

END IF

In the above nested block, the EXIT IF statement exits only the inner IF/THEN block (in which the EXIT statement is located), resulting in execution continuing at the {statements3} portion.  That is, EXIT IF does not exit the overall IF/THEN structure.

Whilst EXIT can provide a convenient mechanism to escape a structure, subtle logic problems can arise when converting a nested single-line IF statement into an IF-block structure.  For example:

IF x&  = 1 THEN

  IF y& = 82 THEN EXIT IF

  y& = 12

END IF

…is not logically equivalent to:

IF x&  = 1 THEN

  IF y& = 82 THEN

    EXIT IF

  END IF

  y& = 12

END IF

Restrictions

Before using EXIT to leave a Function, you should assign the desired function result before EXIT is executed.  By default, the value returned by the function will be zero or an empty string as determined by the Function return type.  For example:

FUNCTION x() AS LONG

  ...

  IF condition THEN

    FUNCTION = -1&

    EXIT FUNCTION ' return -1

  END IF

  ...

END FUNCTION

See also

DO/LOOP, FOR/NEXT, FUNCTION/END FUNCTION, IF/END IF blockITERATE, MACRO/END MACRO, SELECT, SUB/END SUB, TRY/END TRY, WHILE/WEND