how to create a Reference in ST (TC3)

#PLC #TwinCAT3 #Beckhoff

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".

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.

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:

  1. 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.
  2. 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.