IF...THEN...ELSE
The IF statement is used to conditionally execute a statement or a block of statements. The syntax of the IF statement is as follows:
or
The expression after the "IF" is called the condition of the IF statement. This expression (or condition) is evaluated, and if true, the statement following the "THEN" is executed. (See Definition of True and False for details on how the "truth" of an expression is determined.)
For example:
Here, IDL prints "A is two".
If the expression evaluates to a false value, the statement following the "ELSE" clause is executed:
Here, IDL prints "A is not two".
Control passes immediately to the next statement if the condition is false and the ELSE clause is not present.
Note
Another way to write an IF...THEN...ELSE statement is with a conditional expression using the ?: operator. For more information, see Working with Conditional Expressions.
Tip
Programs with vector and array expressions run faster than programs with scalars, loops, and IF statements. See Use Vector and Array Operations for a discussion on increasing efficiency of these expressions.
Using Statement Blocks with the IF Statement
The THEN and ELSE clauses can be in the form of a block (or group of statements) with the delimiters BEGIN and END (see BEGIN...END). To ensure proper nesting of blocks, you can use ENDIF and ENDELSE to terminate the block, instead of using the generic END. Below is an example of the use of blocks within an IF statement.
Nesting IF Statements
IF statements can be nested in the following manner:
If condition P1 is true, only statement S1 is executed; if condition P2 is true, only statement S2 is executed, etc. If none of the conditions are true, statement SX will be executed. Conditions are tested in the order they are written. The construction above is similar to the CASE statement except that the conditions are not necessarily related.