A REFERENCE is an "alias" for an object. You can write or read an alias using identifiers. The difference to a pointer is that you control the value that is referenced directly, and that the assignment of reference and value is fixed. You must set the address of the reference via a separate assignment operation (see Assignment operator REF=). You can check whether a reference points to a valid value (for example: not equal to 0) using a special operator (see Checking for valid references).

Syntax: <Identifier>: REFERENCE TO <data type>

Sample declaration:

nA     : INT;
nB     : INT;

You can now use refInt as "alias" for variables of type INT.

Application example:

refInt REF= nA;       // refInt points now to nA
refInt := 12;         // nA has got the value 12
nB     := refInt * 2; // nB has got the value 24
refInt REF= nB;       // refInt points now to nB
refInt := nA / 2;     // nB has got the value 6
refInt REF= 0;        // explicit initialisation of the reference
References cannot be declared as REFERENCE TO REFERENCE or ARRAY OF REFERENCE or POINTER TO REFERENCE. No references can be declared to BIT variables.
TwinCAT initializes references (with 0).
If a reference to an allocated input variable is used, the access (e.g. ref REF= input;) is interpreted as write access. This is not possible and will cause a compiler error when generating code.

Assignment operator REF=


The operator creates a reference (pointer) to a value.


<Variable1> REF= <Variable2>


    refA  : REFERENCE TO ST_Sample;
    stA   : ST_Sample;
    refB  : REFERENCE TO ST_Sample;
    stB1  : ST_Sample;
    stB2  : ST_Sample;
refA REF= stA;   // represents => refA := ADR(stA);

refB REF= stB1;  // represents => refB := ADR(stB1);
refA := refB;    // represents => refA^ := refB^; (value assignment of refB as refA and refB are implicitly dereferenced)
refB := stB2;    // represents => refB^ := stB2; (value assignment of stB2 as refB is implicitly dereferenced)

Checking for valid references

You can use the operator __ISVALIDREF to check whether a reference points to a valid value, that is a value other than 0.


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

<Boolean variable> becomes TRUE if the reference points to a valid value, otherwise FALSE.



nVar : INT;
bTestref : BOOL := FALSE;
bTestref0 : BOOL := FALSE;


nVar := nVar + 1;
refInt REF= hugo;
refInt0 REF= 0;
bTestref := __ISVALIDREF(refInt); (* becomes TRUE, because refInt points to nVar, which is non-zero *)
bTestref0 := __ISVALIDREF(refInt0); (* becomes FALSE, because refInt is set to 0 *)
The implicit CheckPointer monitoring function affects variables of type REFERENCE in the same way as pointer variables.

See also:

POU CheckPointer