C Language and Libraries Help (clang.hlp) (
Table of Contents;
Topic list)
Important Notice
The pages on this site contain documentation for very old MS-DOS software,
purely for historical purposes.
If you're looking for up-to-date documentation, particularly for programming,
you should not rely on the information found here, as it will be woefully
out of date.
union
◄Example► ◄Up► ◄Contents► ◄Index► ◄Back►
─────C/C++ Language─────────────────────────────────────────────────────────
Keyword: union
Syntax: union [tag] {member-list} [declarators];
[union] tag declarators;
Summary: Declares a union type and/or a variable of a union type.
See: ◄Anonymous Unions►
See also: class, struct
A union is a user-defined data type that can hold values of
different types at different times. It is similar to a structure
except that all of its members start at the same location in
memory. A union variable can contain only one of its members
at a time. The size of the union is at least the size of the
largest member.
A C++ union is a limited form of the class type. It can contain
access specifiers (public, protected, private), member data,
and member functions, including constructors, and destructors.
It cannot contain virtual functions or static data members.
It cannot be used as a base class, nor can it have base classes.
Default access of members in a union is public.
A C union type can contain only data members.
Declaring a Union
Begin the declaration of a union with the union keyword, and
enclose the member list in curly braces:
union UNKNOWN // Declare union type
{
char ch;
int i;
long l;
float f;
double d;
} var1; // Optional declaration of union variable
In C, you must use the union keyword to declare a union variable.
In C++, the union keyword is unnecessary:
union UNKNOWN var2; // C declaration of a union variable
UNKNOWN var3; // C++ declaration of a union variable
Using a Union
A variable of a union type can hold one value of any type
declared in the union. Use the dot operator (.) to access a
member of a union:
var1.i = 6; // Use variable as integer
var2.d = 5.327; // Use variable as double
-♦-