Rules / magic-number
Magic numbers in PLC code: why move a constant to VAR CONSTANT
A raw fractional or large number in an expression does not explain where it came from, and it is easy to miss when a sensor or setpoint changes. A named constant is visible at once and changes in one place.
Severity: Minor
Rule id: magic-number
Magic number: a raw constant in code
What the rule checks
A large/fractional raw constant without a name is easy to miss when changing a setpoint and hard to understand. Move it to a VAR CONSTANT. Array indices, FOR bounds and small integers (<16) don't count; equal constants are grouped by value.
What it does to the plant
A coefficient is changed in one place and forgotten in another, and two loops calculate with different values.
Example
PROGRAM FlowVAR rRaw : REAL; rFlow : REAL;END_VARrFlow := rRaw * 0.0273;
PROGRAM FlowVAR rRaw : REAL; rFlow : REAL;END_VARVAR CONSTANT K_FLOW : REAL := 0.0273;END_VARrFlow := rRaw * K_FLOW;
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
- Declare a named constant and use it:
VAR CONSTANT SEC_PER_HOUR : UDINT := 3600; END_VAR
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
2026-11-26