RAD Studio
ContentsIndex
PreviousUpNext
Unions

Union types are derived types sharing many of the syntactic and functional features of structure types. The key difference is that a union allows only one of its members to be "active" at any one time. The size of a union is the size of its largest member. The value of only one of its members can be stored at any time. In the following simple case,

union myunion {     /* union tag = myunion */
   int i;
   double d;
   char ch;
} mu, *muptr=μ

the identifier mu, of type union myunion, can be used to hold an int, an 8-byte double, or a single-byte char, but only one of these at the same time

Note: Unions correspond to the variant record types of Delphi.
sizeof(union myunion) and sizeof(mu) both return 8, but 4 bytes are unused (padded) when mu holds an int object, and 7 bytes are unused when mu holds a char. You access union members with the structure member selectors (. and ->), but care is needed:

mu.d = 4.016;
printf("mu.d = %f\n",mu.d); //OK: displays mu.d = 4.016printf("mu.i = %d\n",mu.i); //peculiar resultmu.ch = 'A';
printf("mu.ch = %c\n",mu.ch); //OK: displays mu.ch = Aprintf("mu.d = %f\n",mu.d); //peculiar resultmuptr->i = 3;
printf("mu.i = %d\n",mu.i); //OK: displays mu.i = 3

The second printf is legal, since mu.i is an integer type. However, the bit pattern in mu.i corresponds to parts of the double previously assigned, and will not usually provide a useful integer interpretation. 

When properly converted, a pointer to a union points to each of its members, and vice versa.

Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
What do you think about this topic? Send feedback!