TwinCAT Engineering Notes
← All posts

Quirks of VAR_IN_OUT CONSTANT in TwinCAT

An exploration of how the TwinCAT compiler handles VAR_IN_OUT CONSTANT parameters, specifically with string literals and temporary variables.

At first glance, VAR_IN_OUT CONSTANT seems to simply prevent writing to a variable. In reality, its behavior is more subtle.

Any VAR_IN_OUT is a reference to a variable from an outer context. However, for a VAR_IN_OUT CONSTANT of a string type, it is possible to pass a string literal directly into a method. This does not work for other types (numbers, etc.).

I assumed that the compiler creates a temporary variable for the literal and destroys it after the method call. However, experiments showed otherwise: the automatic variable persists, and the data at that address remains accessible.

This means the compiler already implements automatic variable creation for string literals. I think this does not work for other short types because such types can be passed using VAR_INPUT without any performance loss.

It would be nice to have similar behavior for structures and arrays, and support the same functionality for ANY.

The illustration below clarifies the scenario.

VAR_IN_OUT CONSTANT illustration

#TwinCAT #CoDeSys #StructuredText #OOP #IndustrialAutomation