P4022

Code

P4022

Message

Variable initializer type is incompatible with declared type

This error occurs when a variable’s initializer value is not compatible with the variable’s declared type. Each type in IEC 61131-3 accepts only specific kinds of literal values.

Example

The following code will generate error P4022:

PROGRAM main
VAR
    dummy : INT := 10.0;  (* Error: real literal cannot initialize integer type *)
END_VAR
END_PROGRAM

The literal 10.0 is a real (floating-point) value, but INT is an integer type. Real literals can only initialize REAL or LREAL variables.

To fix this error, use a literal that matches the declared type:

PROGRAM main
VAR
    dummy : INT := 10;
END_VAR
END_PROGRAM

Named Constants

An initial value that names a CONSTANT variable (an extension enabled by --allow-constant-initializer-expressions) is checked by the constant’s declared type, as an assignment of that constant would be, rather than by the literal the constant holds. The following code generates error P4022 because a UDINT value cannot be assigned to an INT variable, even though 3 would fit:

PROGRAM main
VAR CONSTANT
    MAX_RETRIES : UDINT := 3;
END_VAR
VAR
    retries : INT := MAX_RETRIES;  (* Error: UDINT constant cannot initialize INT *)
END_VAR
END_PROGRAM

To fix this error, declare the variable with the constant’s type, or with a type the constant’s type widens to:

PROGRAM main
VAR CONSTANT
    MAX_RETRIES : UDINT := 3;
END_VAR
VAR
    retries : UDINT := MAX_RETRIES;
END_VAR
END_PROGRAM

Array Initializers

A list of values in brackets initializes only an array. After the name of a type that is not an array, the list has no elements to initialize. The following code generates error P4022 because Point is a structure:

TYPE
    Point : STRUCT
        x : DINT;
        y : DINT;
    END_STRUCT;
END_TYPE

PROGRAM main
VAR
    origin : Point := [0, 0];  (* Error: Point is not an array *)
END_VAR
END_PROGRAM

To fix this error, initialize a structure with its field names:

TYPE
    Point : STRUCT
        x : DINT;
        y : DINT;
    END_STRUCT;
END_TYPE

PROGRAM main
VAR
    origin : Point := (x := 0, y := 0);
END_VAR
END_PROGRAM

See Also

  • Initial Values — initial values, including named constants

  • Array Types — array initial values

  • P4037 — a constant expression initializer without the flag that enables it

Think IronPLC is wrong about this?

If you believe this diagnostic is incorrect, open an issue on GitHub with a small sample that demonstrates the problem.