ST instruction IF

The IF statement is used to test a condition and to execute the subsequent instructions if the condition is met.

A condition is encoded as a expression that returns a boolean value. If the expression returns TRUE, the condition is met and the associated statements after THEN are executed. If the expression returns FALSE, the following conditions marked ELSIF are evaluated. If an ELSIF condition returns TRUE, the instructions after the associated THEN are executed. If all conditions are FALSE, the statements after ELSE are executed.

So at most one branch of the IF statement is executed. The ELSIF branches and the ELSE branch are optional.

Syntax

IF <condition> THEN
    <statements>
(ELSIF <condition> THEN
    <statements>)*
(ELSE
    <statements>)?
END_IF;

// ( ... )* None, once or several times
// ( ... )? Optional

Sample:

PROGRAM MAIN
VAR
    nTemp       : INT;
    bHeatingOn  : BOOL;
    bOpenWindow : BOOL;
END_VAR
IF nTemp < 17 THEN
    bHeatingOn  := TRUE;
ELSIF nTemp > 25 THEN
    bOpenWindow := TRUE;
ELSE
    bHeatingOn  := FALSE;
    bOpenWindow := FALSE;
END_IF;

At runtime, the program is run through as follows:

If the evaluation of the expression nTemp < 17 = TRUE, the following instruction is executed and the heating is switched on. If the evaluation of the expression nTemp < 17 = FALSE, the following ELSIF condition nTemp > 25 is evaluated. If this is true, the statement under ELSIF is executed and the window is opened. If all conditions are FALSE, the statements under ELSE are executed. The heating is turned off and the window is closed.

See also: