0

Is this legal or recommended? I read that you should only use integer types as bitfields, but does this apply to boolean types? Is this OK, or is this bad practice or undefined behavior somehow?

struct MyStruct {
    // ...
    bool SomeBooleanProperty:1;
    // ...
};
Barmar
  • 741,623
  • 53
  • 500
  • 612
user16217248
  • 3,119
  • 19
  • 19
  • 37

1 Answers1

5

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


.... should I make 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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • 1
    Note that `_Bool` and the int versions behave differently, e.g. `x = 2;` will produce a true `_Bool` but zero for the other types – M.M Jun 24 '21 at 00:44
  • @M.M Agree zero for `bool` and `unsinged`. Likely zero for `signed int` - yet that is an implementation defined conversions. That point does give `bool` an edge. – chux - Reinstate Monica Jun 24 '21 at 02:02