IF .. THEN .. ELSEIF .. ELSE .. ENDIF
Purpose To make a decision regarding program flow based on the result returned by an expression.
Syntax

IF expression_1 [THEN]
.....
[ELSEIF] expression_2 [THEN]
.....
[ELSEIF] expression_N [THEN]
.....

[ELSE]
.....
ENDIF

If the result of expression_1 is non-zero (logical true), the block of program lines between the THEN and the ELSEIF statements will be executed. If the result of expression_1 is zero (false), the block between the IF and ELSEIF will be ignored, and the first ELSEIF expression (expression_2) will be evaluated.

If the result of expression_2 is non-zero (logical true), the block of program lines between the 2nd THEN and the next ELSEIF statement will be executed. If the result of expression_2 is zero (false), the block between the ELSEIF and next ELSEIF will be ignored.

This pattern will repeat for all of the ELSEIF expressions until the last ELSEIF (expression_N) is reached or one of the statements evaluates to a non-zero value (logical true).

If none of the IF or ELSEIF statements evaluate to true, then the block between the ELSE and ENDIF statements will be executed instead. If there is no ELSE statement, and if the result of all the expressions is false, the block of program lines between the first THEN and the ENDIF statement will be ignored, but execution will continue right after the ENDIF statement.

ELSEIF and ELIF:

ELSEIF and ELIF are identical and can be used interchangeably within an IF..ENDIF statement.

ELSEIF or ELIF must be followed by an expression to be evaluated (same syntax as for IF) and on the next line or followed by THEN there should be one or more lines of code to execute should the expression evaluate to true; however, the code is optional.

ELSEIF is not the same as ELSE IF because the space indicates to the compiler that a new nested IF statement is beginning and this would require an ENDIF.

Notes:

Nesting of IF statement Statement blocks within the IF..THEN..ELSEIF..ELSE statement may contain other IF..THEN..ELSEIF..ELSE blocks (nesting).

Each IF statement must be ended with the ENDIF statement. Otherwise an error message "IF without ENDIF" will be reported during compilation. However, the THEN, ELSEIF (or ELIF), and ELSE are all optional.

Testing Equality:

Special comparison operators may be used in the expression of the IF statement. Only integer expression may be compared. For comparison of strings, please refer to the "STRCMP(A$, B$)" function.

Equal

=

Not Equal

<>

Greater than

>

Less than

<

Greater than or Equal to

>=

Less than or Equal to

<=

Examples

IF A >= B*5-20*C OR C=20
   B = B-1
ELSEIF A < D
   B = B + 3
ELIF C = B
   A = C
ELSE
   B = B*3
ENDIF

Comments: A few comparison expressions may be linked with logical-AND (AND statement) or logical-OR (OR statement) operator as shown in the above examples.

backbutton.gif (507 bytes)  Basic to TBASIC Reference Manual