Search code examples
cbit-fields

Integer type of a bitfield


Is the integer type of a bitfield important, or is it basically a throwaway, for example:

struct font {
    int bold : 1;
    int italics : 2;
    int underline : 1;
};

vs.

struct font {
    unsigned int bold : 1;
    unsigned int italics : 2;
    unsigned int underline : 1;
};

vs.

struct font {
    char bold : 1;
    char italics : 2;
    char underline : 1;
};

Does a different integer type 'do' anything here, or is it basically a placeholder?


Solution

  • Whether a bit-field uses a signed or unsigned type makes a different in the values it can hold. In your first example bold can hold the values 0 or -1, while in your second example bold can hold the values 0 and 1.

    The C standard specifically allows int, unsigned int, or _Bool as the type for a bit-field, with support for other types being implementation defined. Most implementations will allow any integer type for a bit-field.

    For those that do, the type specifies the size of the "bucket" the bit-field lives in, so it can affect the size of the struct. On my machine under gcc, the first two structs have size 4 while the third has size 1.