Bit field members
Both C and C++ allow integer members to be stored into memory spaces smaller than the compiler would ordinarily allow. These space-saving structure members are called bit fields, and their width in bits can be explicitly declared. Bit fields are used in programs that must force a data structure to correspond to a fixed hardware representation and are unlikely to be portable.
The constant_expression is a constant integer expression
that indicates the field width in bits. A bit field declaration may
not use either of the type qualifiers const
or volatile
.
Beginning of C only.
In
C99, the allowable data types for a bit field include qualified and
unqualified _Bool
, signed int
, and unsigned
int
. The default integer type for a bit field is unsigned
.
End of C only.
Beginning of C++ only.
A bit field can be any integral type or enumeration type.
End of C++ only.
The maximum bit-field length is 64 bits. To increase portability, do not use bit fields greater than 32 bits in size.
kingdom,
phylum
, and genus
, occupying 12, 6, and
2 bits respectively: struct taxonomy {
int kingdom : 12;
int phylum : 6;
int genus : 2;
};
When you assign a value that is out of range to a bit field, the low-order bit pattern is preserved and the appropriate bits are assigned.
- Define an array of bit fields
- Take the address of a bit field
- Have a pointer to a bit field
- Have a reference to a bit field
If
a series of bit fields does not add up to the size of an int
,
padding can take place. The amount of padding is determined by the
alignment characteristics of the members of the structure. In some
instances, bit fields can cross word boundaries.
Bit fields with a length of 0 must be unnamed. Unnamed bit fields cannot be referenced or initialized.
int
occupies 4 bytes.
The example declares the identifier kitchen
to be
of type struct on_off
: struct on_off {
unsigned light : 1;
unsigned toaster : 1;
int count; /* 4 bytes */
unsigned ac : 4;
unsigned : 4;
unsigned clock : 1;
unsigned : 0;
unsigned flag : 1;
} kitchen;
kitchen
contains eight members totalling
16 bytes. The following table describes the storage that each member
occupies:
Member name | Storage occupied |
---|---|
light |
1 bit |
toaster |
1 bit |
(padding — 30 bits) | To the next int boundary |
count |
The size of an int (4
bytes) |
ac |
4 bits |
(unnamed field) | 4 bits |
clock |
1 bit |
(padding — 23 bits) | To the next int boundary
(unnamed field) |
flag |
1 bit |
(padding — 31 bits) | To the next int boundary |
- "Alignment of bit fields" in the ILE C/C++ Programmer's Guide