Arrays

Topics:

  1. Define array limits via constants [++]
  2. Array lower limit of 1 [+]

Define array limits via constants

You should define the limits of an array using constant variables. When accessing the array within a loop, the same constant variables should be used to define the loop limits.

Note also the following topic of the programming conventions:

General program elements for the following samples:

TYPE ST_Object :
STRUCT
    sName     : STRING;
    nID       : UINT;
END_STRUCT
END_TYPE

Negative sample:

VAR
    aObjects  : ARRAY[1..10] OF ST_Object;
END_VAR

Positive sample:

VAR CONSTANT
    cMin      : UINT := 1;
    cMax      : UINT := 10;
END_VAR
VAR
    aObjects  : ARRAY[cMin..cMax] OF ST_Object;
END_VAR

Array lower limit of 1

For arrays in the IEC 61131 languages, both the upper and lower limits can be defined explicitly. A constant variable with the value 1 should be used as lower limit, so that the number of elements in the array results as upper limit. The upper limit should also be defined by a constant variable.

This is contrary to the lower limit of 0 usually implied in high-level languages. Nevertheless, it is recommended to use a lower limit of 1 to allow a consistent and easy handling of arrays.

Depending on the specific application, other limit values may also be useful. Within a function block, however, it is essential that the method of use is consistent.

Positive sample:

VAR CONSTANT
    cMin         : UDINT := 1;
    cMax         : UDINT := 10;
    cMaxObjects  : UDINT := 10;
END_VAR
VAR
    nIndex       : UDINT;
    aSample      : ARRAY[cMin..cMax] OF REAL;
    aObjects     : ARRAY[cMin..cMaxObjects] OF ST_Object;
END_VAR
FOR nIndex := cMin TO cMax DO
    aSample[nIndex] := 123.456;
END_FOR