Skip to main content

Data Structure: UNION

UNION is a user-defined data structure whose members usually have different data types and sizes.

The members of the instance of a UNION data type all reserve the same memory space. All members have the same address offset and share the memory. The memory requirement is determined by the largest member.

A UNION variable stores the value of exactly one member. The memory contains the last assigned value. This means that the memory is used efficiently.

For more information, see: Object: DUT

Type declaration

Syntax:

TYPE <identifier>

UNION

   <member name> : <data type> := <initialization> ;

END_UNION

END_TYPE

<member name> : <data type> ;

Declaration of a member of an elementary data type

Any number of declarations can follow, but at least 2.

:= <initialization>

Optional

Example 238. Example

Type declaration: U_VAR_12

TYPE U_VAR_12:
UNION
    wVar1: WORD;
    byVar2 : BYTE;
END_UNION
END_TYPE

Type declaration: U_INT_ID

TYPE U_INT_ID:
UNION
    iVar: INT;
    dVar : DINT;
END_UNION
END_TYPE

Type declaration: U_EFFICIENT

TYPE U_EFFICIENT
UNION
    wMember : WORD;
    dwMember : DWORD;
    strMember : STRING := 'A'; 
END_UNION
END_TYPE


Variable declaration

Instantiation/declaration of a variable of a UNION data type:

<variable name> : <name UNION type> := <initialization> ;

:= <initialization>

Optional

:= ( <member name> := <literal> )

Initialization in detail:

The assignment operator is followed by the assignment of the initial value to the member in round brackets.

Example 239. Example
TYPE U_AB:
UNION
    lrA : LREAL;
    liB : LINT;
END_UNION
END_TYPE

Variable declaration with initialization

PLC_PRG PROGRAM
VAR
    uabVAR_1 : U_AB := (lrA := LREAL#1.5);
    uabVAR_2 : U_AB := (liB := LINT#1);
END_VAR


Example 240. Example

Variable declaration in PLC_PRG with data type U_EFFICIENT

PLC_PRG PROGRAM
VAR
 uefficient_1 : U_EFFICIENT := (strMember := 'A');
END_VAR

Implementation: PLC_PRG

uefficient_1.wMember := 16#000A;

When uefficient_1 is written to a member of the variable, this affects all members of the variable.