ReferenceΒΆ

A REFERENCE is also a pointer, but it has some advantages over a POINTER:

You declare a reference in accordance with the following syntax:

Syntax

<identifier> : REFERENCE TO <data type>

Example

A : REFERENCE TO DUT;
B : DUT;
C : DUT;

A REF= B; // corresponds to A := ADR(B);
A := C; // corresponds to A^ := C;

Note

You cannot declare references in the following ways:

  • REFERENCE TO REFERENCE
  • or ARRAY OF REFERENCE
  • or POINTER TO REFERENCE.

Furthermore, you cannot declare a reference to a bit variable.

Hint

CODESYS initializes references (at 0) with compiler version >= V3.3.0.0.

Hint

When a reference is used for a device entry, write access is enabled (for example, ref REF= input;) . This leads to a compiler warning when code is generated : “...invalid assignment target”.

If you require this kind of construct, then first you must copy the input value (input) to a variable with write access.

Checking for valid references

You can use the operator __ISVALIDREF in order to check whether a reference points to a valid value, i.e. to a value not equal to 0.

Syntax:

<Boolean variable> := __ISVALIDREF(<with REFERENCE TO <data type> declared identifier);

<Boolean variable> is TRUE when the reference points to a valid value; otherwise FALSE.

Example

Declaration:

ivar : INT;
ref_int : REFERENCE TO INT;
ref_int0 : REFERENCE TO INT;
testref : BOOL := FALSE;

Implementation:

ivar := ivar + 1;
ref_int REF= ivar;
ref_int0 REF= 0;
testref := __ISVALIDREF(ref_int);  (* becomes TRUE, because ref_int points to ivar, which is non-zero *)
testref := __ISVALIDREF(ref_int0); (* becomes FALSE, because ref_int is set to 0 *)

Note

In compiler version 3.5.7.40 and later, the implicit monitoring function CheckPointer also affects REFERENCE variables the same as pointer variables.

See also