Datasheet

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 mem-
ory space.
Note: The mikroC PRO for AVR does not support anonymous unions (ANSI diver-
gence).
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 dou-
ble
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:
170
MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
Language Reference
mikroC PRO for AVR
CHAPTER 5