Microchip Technology XC8 Standard Compiler (Workstation) SW006021-1 SW006021-1 Manuel D’Utilisation
Codes de produits
SW006021-1
MPLAB
®
XC8 C Compiler User’s Guide
DS52053B-page 150
2012 Microchip Technology Inc.
5.4.4.2
BIT-FIELDS IN STRUCTURES
MPLAB XC8 C Compiler fully supports bit-fields in structures.
Bit-fields are always allocated within 8-bit words, even though it is usual to use the type
unsigned int
unsigned int
in the definition.
The first bit defined will be the LSb of the word in which it will be stored. When a bit-field
is declared, it is allocated within the current 8-bit unit if it will fit; otherwise, a new byte
is allocated within the structure. Bit-fields can never cross the boundary between 8-bit
allocation units. For example, the declaration:
is declared, it is allocated within the current 8-bit unit if it will fit; otherwise, a new byte
is allocated within the structure. Bit-fields can never cross the boundary between 8-bit
allocation units. For example, the declaration:
struct {
unsigned lo : 1;
unsigned dummy : 6;
unsigned hi : 1;
} foo;
will produce a structure occupying 1 byte. If foo was ultimately linked at address 10H,
the field lo will be bit 0 of address 10H; hi will be bit 7 of address 10H. The LSb of
dummy
the field lo will be bit 0 of address 10H; hi will be bit 7 of address 10H. The LSb of
dummy
will be bit 1 of address 10H and the MSb of dummy will be bit 6 of address 10h.
Unnamed bit-fields may be declared to pad out unused space between active bits in
control registers. For example, if dummy is never referenced, the structure above could
have been declared as:
control registers. For example, if dummy is never referenced, the structure above could
have been declared as:
struct {
unsigned lo : 1;
unsigned : 6;
unsigned hi : 1;
} foo;
A structure with bit-fields may be initialized by supplying a comma-separated list of
initial values for each field. For example:
initial values for each field. For example:
struct {
unsigned lo : 1;
unsigned mid : 6;
unsigned hi : 1;
} foo = {1, 8, 0};
Structures with unnamed bit-fields may be initialized. No initial value should be supplied
for the unnamed members, for example:
for the unnamed members, for example:
struct {
unsigned lo : 1;
unsigned : 6;
unsigned hi : 1;
} foo = {1, 0};
will initialize the members lo and hi correctly.
A bit-field that has a size of 0 is a special case. The Standard indicates that no further
bit-field is to be packed into the allocation unit in which the previous bit-field, if any, was
placed.
bit-field is to be packed into the allocation unit in which the previous bit-field, if any, was
placed.