MOULDLKnowledge BaseElectrical Knowledge Base3D Model DownloadsMembership
中文版Model Store »
Knowledge Base › Electrical Knowledge Base › How do you write an IF statement in structured text (ST)?
HomeModels
Table of contents

On this page

PLC & Programming (100 articles)

Quick Reference

  • PLC & Programming
  • Electrical & Electronic Basics (monthly)(每月更新中)
  • Electrical Control & Drawings (monthly)(每月更新中)
  • Drives & Actuators (monthly)(每月更新中)
  • Sensors & Detection (monthly)(每月更新中)
  • Industrial Communication & Networks (monthly)(每月更新中)
  • HMI & Host Systems (monthly)(每月更新中)
  • Industrial Robots & Motion Control (monthly)(每月更新中)
  • Mechatronic System Integration (monthly)(每月更新中)
  • Fault Diagnosis & Standards (monthly)(每月更新中)

How do you write an IF statement in structured text (ST)?

The IF statement is ST's most-used branch. The syntax is easy; the traps are in the details: confusing assignment with comparison, short-circuit evaluation side effects, floating-point equality, and runaway nesting. This article gives the standard form, common variants and four avoidance rules — IFs written this way stay clean.

1. Standard syntax

IF condition1 THEN
  statements;
ELSIF condition2 THEN
  statements;
ELSE
  statements;
END_IF;

Points: ① the condition must be boolean (TRUE/FALSE), built from comparisons and logic; ② ELSIF (one word; not ELSE IF — most platforms accept both but standard style is ELSIF) chains short-circuit in order — once one matches, later ones are not evaluated; ③ ELSE is optional, but control logic should write it (an explicit "everything else" makes missed states visible); ④ END_IF closes every IF — one per nesting level.

2. Building condition expressions

OperationSyntaxNote
Comparison=, <>, >, <, >=, <=Assignment is :=, comparison is = — never mixed
AND / OR / NOTAND, OR, NOTSeries contacts in Mitsubishi terms
Exclusive-orXORHandy for two-way exclusivity
Combinations(A AND B) OR CParentheses beat default precedence — always

Booleans stand alone as conditions: IF AutoMode THEN, not IF AutoMode = TRUE THEN — the latter is verbose and one keystroke from an assignment typo. Negation: IF NOT FeedBack THEN.

3. Four frequent traps

TrapSymptomRule
:= versus = swappedAssignment inside a condition (most platforms refuse; some language versions slip through) or comparison typed as assignmentCompiler warnings fully on; := only in statement territory
Floating-point equalityIF Temp = 50.0 never firesTolerance band: ABS(Temp-50.0) < 0.5
Relying on short-circuitExpecting the AND's right side not to run (especially calls with side effects)Side effects out of conditions; conditions stay pure
Over-nestingFive END_IFs stacked — unchangeableTwo levels max; early RETURN or split conditions

On short-circuiting: most platforms evaluate AND lazily (left FALSE skips the right) — a performance feature and a trap: put a side-effecting call (counting, flag-setting) inside a condition and it "sometimes runs, sometimes doesn't". The condition zone holds pure judgements only.

4. Translating ladder thinking into ST

Ladder "contacts in series + coil" translates to IF + assignment:

(ladder) Start AND no fault → RUN coil
(ST) IF Start AND NOT Fault THEN Run := TRUE; ELSE Run := FALSE; END_IF;
(cleaner) Run := Start AND NOT Fault;  // direct boolean assignment, no IF

Note the third form: a pure boolean expression assigned directly reads better than an IF — and its semantics is "assigned every scan" (following), matching a ladder coil; an IF wrapping only TRUE with no ELSE means "can only set" — different semantics. Translate ladder with direct assignment; use IF+SET thinking for state memory.

5. IF inside state machines

CASE Step OF  // branches first pick CASE, see the companion article
...
END_CASE;
IF Abort THEN Step := 0; END_IF;  // global abort handled by a plain IF

Multi-way branches (steps, modes, states) read better as CASE; IF is left for global aborts, cross-state common conditions and binary choices. IF and CASE each in their lane keep the state machine layered.

6. Common errors

SymptomCauseFix
"Type mismatch" at compileNon-boolean condition (e.g. IF X+1 THEN)Add the comparison operator
Branch never enteredFloating-point = / inverted conditionTolerance band / re-check the logic
Flag occasionally lostSide-effecting call short-circuited on the AND's rightSide effects out of conditions
END_IF mismatchNesting without closingWrite END_IF immediately after IF, then fill in
ELSE branch misses statesNo ELSE, coverage incompleteExplicit ELSE as the control-logic fallback

7. Notes

The difference between good and bad IFs is not syntax but condition design: conditions pure of side effects, booleans used bare, floating point in tolerance bands, nesting within two levels. Hold the four rules and ST's IF beats any ladder contact tower — the first sweetness of moving from ladder to ST.

8. References

IF/ELSIF/END_IF syntax and boolean operations follow IEC 61131-3; short-circuit evaluation behaviour follows each platform's language implementation notes (CODESYS/TwinCAT/AutoShop); floating-point comparison handling follows IEEE 754 and engineering tolerance practice.

9. Cautions

⚠️ Three traps to avoid:
① Side effects (flag-setting, counting) inside condition expressions — short-circuiting makes them intermittent;
② Floating-point = for "in position" — the logic never fires;
③ Five-deep IF nesting — one condition change shakes the whole tower.

Two self-checks per IF: does the condition carry side effects? does the ELSE explicitly cover the rest? Answering "yes" routinely keeps ST code solid.

Related reading

Related 3D models: Ready to build it? Download free 3D models & CAD drawings at MOULDL »
MOULDL · Electrical Knowledge Base · free self-study reference for electrical & automation engineers, 3D CAD models at MOULDL