Mikroelektronika MIKROE-738 Datenbogen
216
mikoC PRO for PIC32
MikroElektronika
Unions
Union types are derived types sharing many of syntactic and functional features of structure types. The key difference
is that a union members share the same memory space.
Note: The mikroC PRO for PIC supports anonymous unions.
Union Declaration
Unions have the same declaration as structures, with the keyword
union
used instead of
struct
:
union tag { member-declarator-list };
Unlike structures’ members, the value of only one of union’s members can be stored at any time. Here is a simple
example:
union myunion { // union tag is ‘myunion’
int i;
double d;
char ch;
} mu, *pm;
The identifier
mu
, of the type
myunion
, can be used to hold a 2-byte
int
, 4-byte
double
or single-byte
char
, but only
one of them at a certain moment. The identifier
pm
is a pointer to union
myunion
.
Size of Union
The size of a union is the size of its largest member. In our previous example, both
sizeof(union myunion)
and
sizeof(mu)
return 4, but 2 bytes are unused (padded) when
mu
holds the
int
object, and 3 bytes are unused when
mu
holds
char
.
Union Member Access
Union members can be accessed with the structure member selectors (
.
and
->
), be careful when doing this:
/* Referring to declarations from the example above: */
pm = μ
mu.d = 4.016;
tmp = mu.d; // OK: mu.d = 4.016
tmp = mu.i; // peculiar result
pm->i = 3;
tmp = mu.i; // OK: mu.i = 3
The third line is legal, since
mu.
i is an integral type. However, the bit pattern in
mu.i
corresponds to parts of the
previously assigned
double
. As such, it probably won’t provide an useful integer interpretation.
When properly converted, a pointer to a union points to each of its members, and vice versa.