Title
Value preservation in enumeration vs. integer bit-fields
Status
open
Section
11.4.10 [class.bit]
Submitter
Geoffrey Romer

Created on 2024-05-13.00:00:00 last changed 2 weeks ago

Messages

Date: 2024-11-03.21:06:22

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.
Date: 2024-05-13.00:00:00

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
  }
History
Date User Action Args
2024-11-03 21:06:22adminsetmessages: + msg7872
2024-05-13 00:00:00admincreate