Справочник Пользователя для ABL electronic PIC Microcontrollers PIC18

Скачать
Страница из 312
Unions
Union types are derived types sharing many of the syntactic and functional fea-
tures of structure types. The key difference is that a union allows only one of its
members to be “active” at any given time, the most recently changed member.
Note: mikroC does not support anonymous unions (ANSI divergence).
Union Declaration
Unions are declared same 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. Let’s have a simple example:
union
myunion {  
// union tag is 'myunion'
int
i;
double
d;
char
ch;
} mu, *pm = μ
The identifier 
mu
, of type 
union myunion
, can be used to hold a 2-byte 
int
, a
4-byte 
double
, or a single-byte 
char
, but only one of these at any given time.
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 an 
int
object, and 3 bytes are unused when 
mu
holds a
char
.
Union Member Access
Union members can be accessed with the structure member selectors (
.
and 
->
),
but care is needed. Check the example on the following page.
MikroElektronika:  Development  tools  -  Books  -  Compilers
79
page
mikroC - C Compiler for Microchip PIC microcontrollers
mikroC
making it simple...