how to create a Reference in ST (TC3)
Learn more at Part 4 - Data types & arrays (IEC 61131-3)
1) Example
PROGRAM MAIN
VAR
// Create a Variable
nVariableInteger : INT := 20;
// Create a Reference and the value
nReference : REFERENCE TO INT REF= nVariableInteger;
END_VAR
//Change the content of nVariableInteger
nReference := 30;
2) Documentation
While a pointer is just a variable with an address, a reference is the object, just with another name, so see it as an "alias".
-
Step1 - Declare the Reference
You declare a reference pretty much in the same way as a pointer, but you use the keywoards REFERENCE TO instead.
-
Step2 - Assign a value to the Reference
When assigning a value to a reference, you use the operator REF=.
In this example we have a reference to an integer, and it's assigned the value nVariableInteger.
When assigning a new value to the reference you don't need to use any dereferencing like with pointers. You just use the variable just like if you would use the normal variable, so again, just see it as an alias for the variable it is a reference for.
- Example - the advantage of using References
REMEMBER: When declaring a reference, you CAN'T assign a reference of a type to a variable of another type.
In this example, we have a DATE_AND_TIME variable and an integer variable.
If I declare a REFERENCE TO AN INTEGER, and try to assign this reference a variable with a type of DATE_AND_TIME the compiler complains and we won't be able to compile our software.
So these are the main advantages of using a reference compared to a pointer:
- Easier to use: You don't need to assign an address of a variable, but you assign the reference directly to the variable you are referencing. When using the reference, you don't need to do any weird de-referencing but can use the reference directly just as if it was the variable.
- It is more type safe: A reference of one type can't be a reference to a variable of another type as we just saw. We get this check directly at compile time.