What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?

The 1 and the 7 are bit sizes to limit the range of the values. They’re typically found in structures and unions. For example, on some systems (depends on char width and packing rules, etc), the code:

typedef struct {
    unsigned char a : 1;
    unsigned char b : 7;
} tOneAndSevenBits;

creates an 8-bit value, one bit for a and 7 bits for b.

Typically used in C to access “compressed” values such as a 4-bit nybble which might be contained in the top half of an 8-bit char:

typedef struct {
    unsigned char leftFour  : 4;
    unsigned char rightFour : 4;
} tTwoNybbles;

For the language lawyers amongst us, the 9.6 section of the C++11 standard explains this in detail, slightly paraphrased:


Bit-fields [class.bit]

A member-declarator of the form

     identifieropt   attribute-specifieropt   :   constant-expression

specifies a bit-field; its length is set off from the bit-field name by a colon. The optional attribute-specifier appertains to the entity being declared. 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 value of the integral constant expression may be larger than the number of bits in the object representation 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 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. – end note

Leave a Comment