Array with variable length
In function blocks, functions or methods, arrays with variable length can be declared in the declaration section VAR_IN_OUT. The operators LOWER_BOUND and UPPER_BOUND can be used to determine the index limits of the array that is actually used at runtime. LOWER_BOUND returns the lower limit, UPPER_BOUND returns the upper limit.
Only statically declared arrays may be passed to an array with variable length. Dynamic arrays created using the __NEW operator must not be passed. |
Syntax for declaring a one-dimensional array of variable length
<variable name> : ARRAY[*] OF <data type> ( := <initialization> )? ;
<data type> : elementary data types | user defined data types | function block types
// (...)? : Optional
Syntax for declaring a multi-dimensional array of variable length
<variable name> : ARRAY[* ( , * )+ ] OF <data type> ( := <initialization> )? ;
<data type> : elementary data types | user defined data types | function block types
// (...)+ : One or more further dimensions
// (...)? : Optional
Syntax of the operators for limit index calculation
LOWER_BOUND( <variable name> , <dimension number> )
UPPER_BOUND( <variable name> , <dimension number> )
Example
The function F_SUM adds the integer values of the array elements and returns the calculated sum as the result. The sum is calculated over all array elements present at runtime. Since the actual number of array elements will only be known at runtime, the local variable is declared as a one-dimensional array of variable length. Arrays with different fixed lengths can be passed to this addition function.
FUNCTION F_Sum : DINT;
VAR_IN_OUT
aData : ARRAY [*] OF INT;
END_VAR
VAR
i, nSum : DINT;
END_VAR
nSum := 0;
FOR i := LOWER_BOUND(aData,1) TO UPPER_BOUND(aData,1) DO
nSum := nSum + aData[i];
END_FOR;
F_Sum := nSum;