プログラミング言語C/C++では、ビット幅が値0の無名(unnamed)ビットフィールドを宣言できる。ゼロ幅ビットフィールドにより、その前後ビットフィールドへの割当バイト(byte)を分離する。
struct S { int b1 : 4; int b2 : 2; int : 0; // (無名)ゼロ幅ビットフィールド int b3 : 2; };
上記例のビットフィールドb1, b2は同一バイト位置に割り当てられるが、ゼロ幅ビットフィールドを挟んだb3は前2つとは異なるバイト位置に割り当てられることが保証される。
C言語
C99 6.7.2.1/p3, 11より一部引用(下線部は強調)。
Syntax
(snip)
struct-declarator:
declarator
declaratoropt:constant-expression3 The expression that specifies the width of a bit-field shall be an integer constant expression with a nonnegative value that does not exceed the width of an object of the type that would be specified were the colon and expression omitted. If the value is zero, the declaration shall have no declarator.
11 A bit-field declaration with no declarator, but only a colon and a width, indicates an unnamed bit-field. As a special case, a bit-field structure member with a width of 0 indicates that no further bit-field is to be packed into the unit in which the previous bit-field, if any, was placed.
C++言語
C++03 9.6/p1-2より引用(下線部は強調)。
1 A member-declarator of the form
identifieropt:constant-expression
specifies a bit-field; its length is set off from the bit-field name by a colon. The bit-field attribute is not part of the type of the class member. The constant-expression shall be an integral constant-expression with a value greater than or equal to zero. The constant-expression may be larger than the number of bits in the object representation (3.9) of the bit-field’s type; in such cases the extra bits are used as padding bits and do not participate in the value representation (3.9) of the bit-field. Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. Bit-fields are packed into some addressable allocation unit. [Note: bit-fields straddle allocation units on some machines and not on others. Bit-fields are assigned right-to-left on some machines, left-to-right on others. ]
2 A declaration for a bit-field that omits the identifier declares an unnamed bit-field. Unnamed bit-fields are not members and cannot be initialized. [Note: an unnamed bit-field is useful for padding to conform to externally-imposed layouts. ] As a special case, an unnamed bit-field with a width of zero specifies alignment of the next bit-field at an allocation unit boundary. Only when declaring an unnamed bit-field may the constant-expression be a value equal to zero.
関連URL