Strings
Topics:
Identifier for size and length specifications
Refer to the size of a string variable in bytes as "Size".
Refer the current length of a string in characters as "Len".
Positive sample:
VAR
sText : T_MaxString;
nTextSize : UDINT;
nTextLen : UDINT;
END_VAR
-------------------------------------------
nTextSize := SIZEOF(sText);
nTextLen := LEN(sText);
Recommended default size
The recommended default size of a string variable is T_MaxString (alias of STRING(255)). This applies to the local declaration of the string as well as to the declaration of the parameter in a function/method.
If another size is fixed for the use case, this should be used as the size limit (example: T_AmsNetId).
The size of T_MaxString is defined as maximum for functions like LEN() and CONCAT() and leads to acceptable performance of regular parameter assignments as "call by value".
Static Analysis:
Thematically recommended Static Analysis rule:
Positive sample:
FUNCTION F_Sample : BOOL
VAR_INPUT
sParam1 : T_MaxString;
sParam2 : T_AmsNetId;
END_VAR
PROGRAM MAIN
VAR
sLocal1 : T_MaxString;
sLocal2 : T_AmsNetId;
bReturn : BOOL;
END_VAR
bReturn := F_Sample(sParam1 := sLocal1,
sParam2 := sLocal2);
Transfer of large strings
If a larger string than T_MaxString is required, the transfer should be used as "call by reference". This can be achieved using either VAR_IN_OUT CONSTANT for read-only access or POINTER TO STRING.
An input parameter as REFERENCE TO STRING(1023) is only suitable to a limited extent, because this would always require a fixed size of the assigned variable. If this restriction is acceptable or desired, prefer this variant.
Positive sample:
FUNCTION F_Sample : BOOL
VAR_IN_OUT CONSTANT
sLonger1 : STRING;
END_VAR
VAR_INPUT
pLonger2 : POINTER TO STRING;
nLonger2Size : UDINT;
END_VAR
PROGRAM MAIN
VAR
sLocal : STRING(1023);
bReturn : BOOL;
END_VAR
bReturn := F_Sample(sLonger1 := sLocal,
pLonger2 := ADR(sLocal),
nLonger2Size := SIZEOF(sLocal));
Processing of large strings
When using T_MaxString or smaller string variables, you can use string functions like CONCAT() or LEN() (Tc2_Standard).
For larger string variables you have to use functions like CONCAT2() or LEN2() (Tc2_Utilities).