C allows an area of memory to be occupied by data of several types, though only one at a time, using a union. Unions are syntactically similar to structures:
union number { char c; int i; float f; double d; };
This declares a type called union number
(NB:
‘union
’ is part of the name;
number
is known as the
union's tag).
Members of a C union are accessed using the
.
operator, just as structure
members are accessed:
union number n; int j; n.i = 10; j = n.i;
Only the member to which a value was last assigned contains valid information to be read. There is no way to determine that member implicitly, so the programmer must take steps to identify it, for example, by using a separate variable to indicate the type:
union number n; enum { CHAR, INT, FLOAT, DOUBLE } nt; n.i = 10; nt = INT; switch (nt) { case CHAR: /* accessn.c
*/ break; case INT: /* accessn.i
*/ break; case FLOAT: /* accessn.f
*/ break; case DOUBLE: /* accessn.d
*/ break; }
Java does not have unions, although it is possible for
a reference to refer to any class derived from its own
class. A reference of type Object
can refer to
any class of object, since all classes are originally
derived from Object
.