This is an unofficial snapshot of the ISO/IEC JTC1 SC22 WG21 Core Issues List revision 116a. See http://www.open-std.org/jtc1/sc22/wg21/ for the official list.

2024-12-19


2950. Value preservation in enumeration vs. integer bit-fields

Section: 11.4.10  [class.bit]     Status: open     Submitter: Geoffrey Romer     Date: 2024-05-13

Subclause 11.4.10 [class.bit] paragraph 4 specifies:

If a value of integral type (other than bool) is stored into a bit-field of width N and the value would be representable in a hypothetical signed or unsigned integer type with width N and the same signedness as the bit-field's type, the original value and the value of the bit-field compare equal. 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 compare equal. If a value of an enumeration type is stored into a bit-field of the same type and the width is large enough to hold all the values of that enumeration type (9.7.1 [dcl.enum]), the original value and the value of the bit-field compare equal.

Thus, for bit-fields of integral type, it is sufficient for the actual value to fit into the bit-field. In contrast, for bit-fields of enumeration type, all values of the enumeration type are required to fit even if the actual value being stored is small and would fit. For example:

  enum E : uint8_t { E0 = 0, E1 = 1 };
  struct S {
    int i : 1;
    E e : 1;
  };

  void f() {
    S s = { .i = 1, .e = 1 };
    assert(s.i == 1);    // guaranteed to hold
    assert(s.e == 1);    // may not hold
  }

Suggested resolution:

Change in 11.4.10 [class.bit] paragraph 4 as follows:

If a value of integral type (other than bool) or of enumeration type is stored into a bit-field of width N and the value would be representable in a hypothetical signed or unsigned integer type with width N and the same signedness as the bit-field's type or, respectively, its underlying type, the original value and the value of the bit-field compare equal. 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 compare equal. If a value of an enumeration type is stored into a bit-field of the same type and the width is large enough to hold all the values of that enumeration type (9.7.1 [dcl.enum]), the original value and the value of the bit-field compare equal.