11.2 If-EndIf statement

There are two versions of the If statement: A long and a short version.

1) Long version If statement:

If <expr> <block> [ElseIf <expr> <block> ...] [Else <block>] EndIf

The If statement checks if the given expression is true (non-zero). If this is the case, the commands following the statement are executed. If the given expression is false (zero), If jumps to the next ElseIf statement (if there is any) and checks if the expression given there is true. This is repeated until the Else statement is reached. If none of the expressions before was true, the code following Else will be executed.

The statements If and EndIf are obligatory. ElseIf and Else statements are optional. You can use as many ElseIf's as you like but there must be only one Else in your If statement. Furthermore, the Else statement must be the last condition before EndIf. Here is an example:

If a > 5                       ; check if a is greater than 5
    DebugPrint("a > 5")
ElseIf a < 5                   ; check if a is less than 5
    DebugPrint("a < 5")
Else                           ; else a must be 5
    DebugPrint("a = 5")

You can also use more complex expressions as the condition:

If country$ = "USA" And age < 21
    DebugPrint("No alcohol permitted under 21 in the USA!")

2) Short version If statement:

If <expr> Then <true-stat> [ElseIf <expr> <true-stat> ...] [Else <stat>]

The short version of the If statement works in the same way as the long version but has the advantage that you do not need to include an EndIf. The short If statement has the restriction, that all of its parts have to be placed on a single line. Another restriction is, that only one statement must follow the Then / ElseIf / Else identifiers. If you want to execute multiple statements you have to use the long version.

Using the short If statement we could write the example from above in the following way:

If a>5 Then Print("a>5") ElseIf a<5 Print("a<5") Else Print("a=5")

You can see that the result is not very readable, so in the case of the example from above, it is not recommended to use the short version. The short If statement does better fit if you just have one condition, e.g.

If a = True Then b = 5

This is better readable than

If a = True
    b = 5

Another version of the If statement is the so called immediate-if statement IIf(). This version is implemented as a command in Hollywood and it is part of the system library. See IIf for details.

Show TOC