5

Possible Duplicate:
C++ bitfield packing with bools

Is it guaranteed to be safe to use C++'s bool keyword inside a bitfield definition?

Something like:

struct flags {
    bool a : 1;
    bool b : 1;
}
Cœur
  • 34,719
  • 24
  • 185
  • 251
Eric
  • 791
  • 6
  • 15
  • 2
    Some answers here: [C++ bitfield packing with bools](http://stackoverflow.com/questions/308364/c-bitfield-packing-with-bools) may help you. Why do you want to do it in the first place? – Carl Norum Nov 01 '12 at 04:50

2 Answers2

6

From C++03 9.6 "Bit-fields":

A bit-field shall have integral or enumeration type (3.9.1). It is implementation-defined whether a plain (neither explicitly signed nor unsigned) char, short, int or long bit-field is signed or unsigned. A bool value can successfully be stored in a bit-field of any nonzero size. ...

If the value true or false is stored into a bit-field of type bool of any size (including a one bit bit-field), the original bool value and the value of the bit-field shall compare equal. ...

3.9.1/7 "Fundamental types" specifies that bool is an integral type.

Michael Burr
  • 321,763
  • 49
  • 514
  • 739
5

Yes. In practice, you can use sizeof(bool) * CHAR_BIT as your guide to knowing how many bits are available.

From C++98, § 9.6.3

A bit-field shall have integral or enumeration type (3.9.1).

From C++98, § 3.9.1.7

Types bool, char, wchar_t, and the signed and unsigned integer types are collectively called integral types

Brian Cain
  • 13,996
  • 3
  • 46
  • 85