IF

The IF instruction executes a group of statements conditionally.

Syntax

IF condition THEN
   statement
   [...]
[ ELSE
   statement
   [...]
]
END IF
  1. condition is a boolean expression.
  2. statement is any instruction supported by the language.

Usage

By default, the runtime system evaluates all part of the condition. The semantics of boolean expressions can be controlled by the OPTIONS SHORT CIRCUIT compiler directive, to reduce expression evaluation when using AND / OR operators.

If condition is TRUE, the runtime system executes the block of statements following the THEN keyword, until it reaches either the ELSE keyword or the END IF keywords and resumes execution after the END IF keywords.

If condition is FALSE, the runtime system executes the block of statements between the ELSE keyword and the END IF keywords. If ELSE is absent, it resumes execution after the END IF keywords.

A NULL expression is considered as FALSE.
Important: Use the IS NULL or IS NOT NULL keywords to test if an expression is null or not null.

The following code example displays FALSE:

DEFINE var STRING
LET var = NULL
IF var THEN        -- Bad practice!
   DISPLAY "TRUE"
ELSE
   DISPLAY "FALSE"
END IF
The next example displays nothing, because both boolean expressions evaluate to null and then we do not enter in the IF block:
DEFINE var STRING
LET var = NULL
IF var THEN        -- Bad practice!
   DISPLAY "TRUE"
END IF
IF NOT var THEN    -- Bad practice!
   DISPLAY "FALSE"
END IF
In this example, using the "" string literal in the comparison expression results to NULL and is also a bad practice:
DEFINE var STRING
LET var = NULL
IF var == "" THEN  -- Bad practice!
   DISPLAY "You will not see this"
END IF
Consider using the IS NULL operator or, for strings that can contain blanks, check if the LENGTH() function returns zero:
DEFINE var STRING
LET var = NULL
IF var IS NULL THEN
   DISPLAY "NULL string"
END IF
LET var = "   "
IF LENGTH(var)==0 THEN
   DISPLAY "String in empty, NULL or contains only blanks"
END IF

Example

MAIN
  DEFINE name CHAR(20)
  LET name = "John Smith"
  IF name MATCHES "John*" THEN
    DISPLAY "The name starts with [John]!"
  ELSE
    DISPLAY "The name is " || name || "."
  END IF
END MAIN