Constants are identifiers for unchangeable values. You can declare constants locally
within a POU or globally within a global variable list. The declaration segment is
extended with the keyword CONSTANT
.
Constants are also strings that represent the value of a base type, such as integers
or floating-point numbers (for example, 16#FFFF_FFFF
, T#5s
, or -1.234 E-5
). To distinguish between them, these constants are also called literals, literal
constants, or unnamed constants. There are logical (TRUE
, FALSE
) or numeric literals (3.1415
, T#5s
), but also string literals ('Hello world!'
, "black"
).
Syntax declaration
<scope> CONSTANT <identifier> : <data type> := <initial value> ; END_VAR <scope> : VAR | VAR_INPUT | VAR_STAT | VAR_GLOBAL <data type>: <elementary data type | user defined data type | function block > <initial value> : literal value | identifier | expression
Allowed initial values:
-
Literal
Examples:
TRUE
,FALSE
,16#FFFF_FFFF
-
Named constant that was declared at another location
-
Simple expression composed of literals, also combined with simple operators, such as + - *
Inputs or function calls cannot be specified as an initial value.
Example
VAR_GLOBAL CONSTANT g_ciMAX_A : INT := 100; g_ciSPECIAL : INT := g_ciMAX_A - 10; END_VAR
Constants are defined only for the declaration. The assignment of an initial value is required. Within an implementation, constants are only read and therefore always appear on the right of the assignment operator in a statement.
The constants are replaced with the initial value when the code is compiled. It also has to be possible to calculate the initial value at compile time.
Constants of structured or user-defined types are calculated not until runtime. Structured constants in programs or GVLs are calculated one time at program start. Structured constants in functions or methods are calculated every time the function or method is called. Therefore, the initialization of structured constants can depend on inputs or execute function calls.