SIZEOF返回的是变量占用的字节数,不是数组的元素个数。
官方文档出处: Operator ‘SIZEOF’
This operator is used for defining the number of bytes that are required by the variable x. The SIZEOF operator always yields an unsigned value. The type of return variable adapts to the detected size of the variable x.
对于可变数组,可以用UPPER_BOUND与LOWER_BOUND函数来获取可变数组的上边界与下边界,从而获取到可变数组长度。
官方文档出处: Data Type ‘ARRAY’
The SUM function adds the integer values of the array elements and returns the calculated sum as a result. The sum is calculated across all array elements available at runtime. The sum is calculated across all array elements available at runtime. As 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.
FUNCTION SUM: INT;
VAR_IN_OUT
aiData : ARRAY OF INT;
END_VAR
VAR
diCounter, diResult : DINT;
END_VAR
diResult := 0;
FOR diCounter := LOWER_BOUND(aiData, 1) TO UPPER_BOUND(aiData, 1) DO // Calculates the length of the current array
diResult := diResult + A[i];
END_FOR;
SUM := diResult;
|