C++ Programming/Programming Languages/C++/Code/Keywords/union

The union keyword is used to define a union type.


 * Syntax:

Union is similar to  (more than  ), unions differ in the aspect that the fields of a   share the same position in memory and are by default   rather than. The size of the  is the size of its largest field (or larger if alignment so requires, for example on a SPARC machine a   contains a   and a   so its size is likely to be 24 because it needs 64-bit alignment). Unions cannot have a.

What is the point of this? Unions provide multiple ways of viewing the same memory location, allowing for more efficient use of memory. Most of the uses of unions are covered by object-oriented features of C++, so it is more common in C. However, sometimes it is convenient to avoid the formalities of object-oriented programming when performance is important or when one knows that the item in question will not be extended.

The use of  is covered in greater detain in the Unions Section.