Union type

In computer science, a union is a value that may have any of multiple representations or formats within the same area of memory; that consists of a variable that may hold such a data structure.

In contrast with a record, which could be defined to contain both a float and an integer; a union would hold only one at a time.

A union can be pictured as a chunk of memory that is used to store variables of different data types.

Because of the limitations of their use, untagged unions are generally only provided in untyped languages or in a type-unsafe way (as in C).

However, one useful programming function of unions is to map smaller data elements to larger ones for easier manipulation.

ALGOL 68 has tagged unions, and uses a case clause to distinguish and extract the constituent type at runtime.

An example is: The syntax of the C/C++ union type and the notion of casts was derived from ALGOL 68, though in an untagged form.

[1] In C and C++, untagged unions are expressed nearly exactly like structures (structs), except that each data member is located at the same memory address.

A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit-field, then to the unit in which it resides), and vice versa.In C++, C11, and as a non-standard extension in many compilers, unions can also be anonymous.

[3] In compilers such as GCC, Clang, and IBM XL C for AIX, a transparent_union attribute is available for union types.

It is mainly intended for function with multiple parameter interfaces, a use necessitated by early Unix extensions and later re-standardisation.

In the example code below, data item VERS-NUM is defined as a 2-byte binary integer containing a version number.

A second data item VERS-BYTES is defined as a two-character alphanumeric variable.

The following example shows the non-standard absolute form: In the first example, each of the elements of the array B maps to one of the specific bytes of the variable A.

Unlike enumerated types in most other languages, enum variants in Rust can contain additional data in the form of a tuple or struct, making them tagged unions rather than simple enumerated types.

[10] In C and C++, the syntax is: A structure can also be a member of a union, as the following example shows: This example defines a variable uvar as a union (tagged as name1), which contains two members, a structure (tagged as name2) named svar (which in turn contains three members), and an integer variable named d. Unions may occur within structures and arrays, and vice versa: The number ival is referred to as symtab[i].u.ival and the first character of string sval by either of *symtab[i].u.sval or symtab[i].u.sval[0].