There have historically been two common ways of interpreting the types of bitfield elements:
Examine whether the type is signed or unsigned, but ignore distinctions
between "char", "short", "int", etc. in deciding where an element should be
placed.
Unless a bitfield is preceded by another with the same type, or the
corresponding signed/unsigned type, allocate an object of that type and
place the bitfield within it. Place following bitfields with the same
type in that object if they fit.
I think the motivation behind #2 was that on a platform where 16-bit values need to be word-aligned, a compiler given something like:
struct foo {
char x; // Not a bitfield
someType f1 : 1;
someType f2 : 7;
};
might be able to allocate a two-byte structure, with both fields being placed in the second byte, but if the structure had been:
struct foo {
char x; // Not a bitfield
someType f1 : 1;
someType f2 : 15;
};
it would be necessary that all of f2
fit within a single 16-bit word, which would thus necessitate a padding byte before f1
. Because of the Common Initial Sequence rule, f1
must be placed identically in those two structures, which would imply that if f1
could satisfy the Common Initial Sequence rule, it would need padding before it even in the first structure.
As it is, code which wants to allow the denser layout in the first case can say:
struct foo {
char x; // Not a bitfield
unsigned char f1 : 1;
unsigned char f2 : 7;
};
and invite the compiler to put both bitfields into a byte immediately following x
. Since the type is specified as unsigned char
, the compiler need not worry about the possibility of a 15-bit field. If the layout were:
struct foo {
char x; // Not a bitfield
unsigned short f1 : 1;
unsigned short f2 : 7;
};
and the intention was that f1
and f2
would sit in the same storage, then the compiler would need to place f1 in a way that could support a word-aligned access for its "bunkmate" f2
. If the code were:
struct foo {
char x; // Not a bitfield
unsigned char f1 : 1;
unsigned short f2 : 15;
};
then f1
would be placed following x
, and f2
in a word by itself.
Note that the C89 Standard added a syntax to force the layout that prevent f1
from being placed in a byte before the storage used f2
:
struct foo {
char x; // Not a bitfield
unsigned short : 0; // Forces next bitfield to start at a "short" boundary
unsigned short f1 : 1;
unsigned short f2 : 15;
};
The addition of the :0 syntax in C89 largely eliminates the need to have compilers regard changing types as forcing alignment, except when processing old code.
_Bool
,signed int
,unsigned int
, or some other implementation-defined type. It is implementation-defined whether atomic types are permitted."