 If instruction if expression[;] then[;] instruction
[else[;] instruction]
The if construct is used to conditionally execute an instruction or group of instructions. It can also be used to select between two alternatives. The expression is evaluated and must result in either 0 or 1. If the result was 1 (true) then the instruction after the then is executed. If the result was 0 (false) and an else was given then the instruction after the else is executed. Example: if answer='Yes' then say 'OK!' else say 'Why not?' Remember that if the else clause is on the same line as the last clause of the then part, then you need a semicolon to terminate that clause. Example: if answer='Yes' then say 'OK!'; else say 'Why not?' The else binds to the nearest then at the same level. This means that any if that is used as the instruction following the then in an if construct that has an else clause, must itself have an else clause (which may be followed by the dummy instruction, nop). Example: if answer='Yes' then if name='Fred' then say 'OK, Fred.' else say 'OK.' else say 'Why not?' To include more than one instruction following then or else, use a grouping instruction (do, loop, or select). Example: if answer='Yes' then do say 'Line one of two' say 'Line two of two' end In this instance, both say instructions are executed when the result of the if expression is 1. Notes: - An instruction may be any assignment, method call, or keyword instruction, including any of the more complex constructions such as do, loop, select, and the if instruction itself. A null clause is not an instruction, however, so putting an extra semicolon after the then or else is not equivalent to putting a dummy instruction (as it would be in C or PL/I). The nop instruction is provided for this purpose.
- The keyword then is treated specially, in that it need not start a clause. This allows the expression on the if clause to be terminated by the then, without a ';' being required -- were this not so, people used to other computer languages would be inconvenienced. Hence the symbol then cannot be used as a variable name within the expression.[1]
|