Retain Variable - RETAIN

Retain variables are declared by the keyword RETAIN is added in programming objects in the scope VAR, VAR_INPUT, VAR_OUTPUT, VAR_IN_OUT, VAR_STAT, or VAR_GLOBAL.

Syntax in the declaration

<scope> RETAIN
    <identifier>: <data type> ( := <initialization> )? // ( ... )? : Optional
END_VAR
<scope> : VAR | VAR_INPUT | VAR_OUTPUT | VAR_IN_OUT | VAR_STAT | VAR_GLOBAL

An assignment of inputs, outputs, or memory addresses with the AT keyword is not permitted.

Example

In a POU:

VAR RETAIN
    iVarRetain: INT;
END_VAR

In a GVL:

VAR_GLOBAL RETAIN
    g_iVarRetain: INT;
END_VAR

Possible declaration locations

Locally in a program Only the variable lies within the retain memory area.
Globally in a global variable list Only the variable lies within the retain memory area.
Locally in a function block The entire instance of the function block with all of its data lies within the retain memory area. Only the declared retain variable is protected.
Locally in a function Even the variable does not lie within the retain memory area. This declaration does not have any effect.
Locally and persistently in a function Even the variable does not lie within the retain memory area. This declaration does not have any effect.

Note

Whenever possible, avoid marking variables of a function block with RETAIN.

See also