PLC

Declaring variables

 

Variable Declaration

In TwinCAT 3 PLC projects, you can declare variables in the following places:

Declaration part of a POU
DUT or GVL editor
Dialog Auto Declare

The declaration editor is used for the variable declarations in global variable lists (GVL) and in the declaration part of POUs. Special editors or dialogs available for all other variants.

 
The properties of one or several variables can be influenced by adding pragmas. More detailed information can be found in section “Using pragmas”.

Syntax for variable declarations in POUs or global variable lists, if the text-based option is selected for the declaration editor:

<Identifier> {AT <Address>}:<Data type> {:=<Initialization>};

<Identifier>: Name of the variable. It is important to follow the rules listed in section “Identifier” when assigning the identifiers. Additional harmonization conventions can be found in section “Identifier/name”.
{AT <Address>} (optional): The keyword AT can be used to link a variable directly to a particular address.
<Data type>: Data type of the variable.
{:=<Initialization>} (optional): Initial value of the variable.
 
 

Variable initialization

The standard initialization value for all declarations is 0. In the declaration part you can specify user-defined initialization values for each variable and each data type.

The user-defined initialization starts with the assignment operator := and consists of a valid expression in the programming language ST (Structured Text). The initialization value is thus defined with the aid of constants, other variables or functions. If you use a variable, this also has to be initialized.

Examples:

VAR
    nVar1 : INT := 12; (*initialization value 12*)
    nVar2 : INT := 13 + 8; (* initialization value defined by an expression of constants*)
    nVar3 : INT := nVar2 + F_Fun(4); (*initialization value defined by an expression, that contains a function call; notice the order!*)
    pSample : POINTER TO INT := ADR(nVar1); (*not described in the standard IEC61131-3: initialization value defined by an adress function; Notice: the pointer will not be initialized during an Online Change*)
END_VAR
 

See also:

Reference Programming > Data types
Reference Programming > Variable types and special variables
Reference Programming > Operands > Addresses
Reference Programming > Identifier
TwinCAT 3 programming conventions > Identifier/name
Additional information
Using the Declaration Editor
Using the Auto Declare dialog
Declaring an array
Declaring global variables