Reference¶
A REFERENCE
is an ‘alias’ for an object. You can write or read an alias with the help of identifiers. The difference between a reference and a pointer is that with a reference you directly control the value that is referenced and the assignment of reference and value is fixed. You must set the address of the reference via a separate assignment operation. You can check with the help of a special operator whether a reference points to a valid value (for example not equal to 0), see below: ‘Checking for valid references’.
You declare a reference in accordance with the following syntax:
Syntax
<identifier> : REFERENCE TO <data type>
Example declaration
ref_int : REFERENCE TO INT;
a : INT;
b : INT;
You can now use ref_int
as an ‘alias’ for variables of the type INT.
Application example
ref_int REF= a; (* ref_int points now to a *)
ref_int := 12; (* a has got the value 12 *)
b := ref_int * 2; (* b has got the value 24 *)
ref_int REF = b; (* ref_int points now to b *)
ref_int := a / 2; (* b has got the value 6 *)
ref_int REF = 0; (* explicit initialisation of the referencee *)
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.
Attention
With compiler versions >= V 3.3.0.0 CODESYS initializes references (with 0).
Attention
If a reference to a device input is used, the access (for example ref REF := input;
) is considered to be a write access. When generating code this leads to a compiler warning "….no valid assignment target"
.
If you require a construct of this kind, you must first 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> goes TRUE if 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;
END_VAR
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
For complier version 3.5.7.40 and later, the implicit check function Checkpointer also acts on REFERENCE
variables in the same way as on pointer variables.
See also