C++ Logo

std-discussion

Advanced search

Storing to truncated enum bitfields

From: Christopher Hallock <christopherhallock_at_[hidden]>
Date: Wed, 10 Apr 2024 17:26:03 -0400
[class.bit]/4 <https://timsong-cpp.github.io/cppwp/class.bit#4.sentence-3>
says:
"[...] 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 ([dcl.enum]), the original value and the value of the
bit-field compare equal."

Why does this say "all the values of that enumeration type" instead of
simply "the original value"? Should this choice of wording be taken to
imply that if the bit-field width is not large enough to hold all the
values of the enumeration, then even storing a specific value that
logically should fit is nonetheless UB or lossy?

In other words, in the example below, can f() return false or trigger UB?

enum E { e0, e1, e2 };
struct S { E bitfield : 1; }; // can't hold all values of E
bool f() {
    S s{e0};
    return s.bitfield == e0;
}

Received on 2024-04-10 21:26:20