Rules / for-unsigned-minus-one
FOR i := 0 TO n - 1 with an unsigned n: a 65535-iteration loop
If n is a WORD or UINT equal to zero, n - 1 wraps through zero to the type maximum. A loop that should not run at all runs tens of thousands of times in one scan.
Severity: Warning
Rule id: for-unsigned-minus-one
Loop up to X - 1 with an unsigned X
What the rule checks
The upper bound X - 1 with an unsigned X (UINT, WORD, UDINT, DWORD and the like) is never negative: with X = 0 the subtraction wraps around and yields the type's maximum, 65535 for a WORD. A loop that should not run at all runs tens of thousands of times per scan: the cycle time blows past the watchdog, and if the counter indexes an array, reads and writes go far beyond its bounds (without CheckBounds that corrupts neighbouring memory). The rule stays silent if X is a constant or the project somewhere checks X > 0, X >= 1, X <> 0, X = 0 or clamps X := MAX(…)/LIMIT(…). Most often X is a unit count entered on the HMI: during commissioning or after replacing the controller, zero is its most likely value.
What it does to the plant
The cycle time blows past the watchdog, and the index runs far beyond the array, corrupting memory.
Example
VAR_GLOBAL wUnits : WORD; aUnitFault : ARRAY[0..15] OF BOOL;END_VARPROGRAM ScanUnitsVAR i : WORD; xAnyFault : BOOL;END_VARxAnyFault := FALSE;FOR i := 0 TO gvl.wUnits - 1 DO xAnyFault := xAnyFault OR gvl.aUnitFault[i];END_FOR
VAR_GLOBAL wUnits : WORD; aUnitFault : ARRAY[0..15] OF BOOL;END_VARPROGRAM ScanUnitsVAR i : WORD; xAnyFault : BOOL;END_VARxAnyFault := FALSE;IF gvl.wUnits > 0 THEN FOR i := 0 TO gvl.wUnits - 1 DO xAnyFault := xAnyFault OR gvl.aUnitFault[i]; END_FOREND_IF
Both listings are run through the linter by an automated test: the rule fires on the first and stays silent on the second.
How to fix
- Wrap the loop in
IF X > 0 THEN … END_IFor clamp the value where it is entered:X := LIMIT(1, X, N_MAX);. - If X indexes an array, check the upper end too:
X - 1must not exceed the array's declared bound.
Upload a PLCopen XML or CODESYS .export file: the report is free and the code is not stored.
The same linter without uploading a file: command line and GitHub Action.
Related rules
In-depth article
2026-11-26