Search code examples
cstructbooleanbit-fields

Can I make bools bit fields?


Is this legal? I read that you can only use integers as bitfields, but does this apply to the bool/_Bool types? Is this OK, or is this undefined behavior somehow?

struct MyStruct {
    // ...
    bool SomeBooleanProperty:1;
    // ...
};

Although this works on GCC and Clang, is this guaranteed to work everywhere that supports C99?


Solution

  • Can ... I make bools bit fields?

    Yes. It is one of 3 well defined choices.

    A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type. It is implementation-defined whether atomic types are permitted. C17dr § 6.7.2.1 5


    But as to whether you should bools bit fields, yes, if it makes code more clear.

    Note: this is one place to not use int x:1 as it is implementation defined if x has values [0,1] or [-1,0]. Use signed int x:1 or unsigned x:1 or _Bool x:1 for [-1,0], [0,1], [0,1] respectively.

    For x:1, bool does have a clearer functionally specification than signed int when assigning an out-of-range value. See comment. For unsigned, just the LSbit is copied.