Union

Return to Glossary

A Union is like a data structure in that it generally has several fields, all of which are public by default. Unlike a struct, however, only one of the fields is used at any given time. In other words, it is a structure that allows the same storage space to be used to store values of different data types at different times. Thus it is necessary, and the programmer's responsibility, to keep track of what is actually stored in the union at any given time.

Unions can be used to conserve memory when a structure is needed in which several pieces of information of different types must be represented but only one will be used at a time, as when the components of a container must contain values of differing data types.

Source: Union