TwinCAT Engineering Notes
← All posts

Ignoring Method Parameters Using Special Values

Elegant approaches to ignore parameters or retain previous values in TwinCAT / CoDeSys using REFERENCE TO and quiet NaN (Not a Number).

Imagine you have a method with a set of parameters, and you need values for these parameters that mean: “use the previous value (or the default value if no previous value exists)”.

How do you solve this? Typically, you can use dedicated sentinel values outside the normal operating range — for instance, 0 for speed, an empty string for text, a special enumeration value (ENUM), or additional boolean flags like ignoreXxxParameter.

However, there are more elegant solutions that can fit your needs in certain scenarios:

1. Using REFERENCE TO (or POINTER TO)

In this case, an unassigned reference or null pointer signifies that the parameter should be ignored. The method implementation looks something like this:

METHOD StartAbsoluteMotion(targetPosition : REFERENCE TO LREAL)
BEGIN
  IF __ISVALIDREF(targetPosition) THEN
    MoveAbsoluteInstance.Position := targetPosition;
  END_IF
  
  MoveAbsoluteInstance(Execute := TRUE);
END

Drawback of this approach: You cannot directly pass literals (except strings), nor can you call another method or property inline to supply the parameter value. Therefore, a call like StartAbsoluteMotion(targetPosition := GetTargetPosition()) will fail to compile due to TwinCAT compiler restrictions.

2. Using Special Floating-Point Values

An example of such a value is the so-called quiet NaN (Not A Number).

Drawbacks of this approach: It only works for REAL and LREAL data types. Additionally, TwinCAT lacks a built-in NAN constant, though you can produce one using mathematical operations with undefined results, such as LOG(-1) or SQRT(-1).

Below is a screenshot demonstrating both approaches in practice:

Ignoring method parameters with special values

#TwinCAT #CoDeSys #PLC #StructuredText #IndustrialAutomation #Beckhoff #OOP