C++ Logo


Advanced search

Subject: New Issue?: [class.bit] p.4 - silent UB and necessary restriction?
From: Peter Sommerlad (C++) (peter.cpp_at_[hidden])
Date: 2021-02-05 06:35:17


while discussing MISRA C++ rules wrt bit fields we came across the
following (slightly changed in C++20) sentence [class.bit] p.4:

"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), the original value and the value of the
bit-field compare equal."

This silently introduces UB, if the bit field is narrower as the
underlying type.

For an enumeration type with a specified underlying type that by
definition can represent all of its values, does that mean a bit field
must not be shorter than the underlying type to make it useful. Or does
it mean, only the named enumerators can be stored to be no UB.

std::byte a:4;

can I ever access a and compare it with std::byte{0} ?

Wouldn't it be useful to allow shorter bit fields for enumeration types
and allow values that fit to be taken out of the bitfield?


Peter Sommerlad
Better Software: Consulting, Training, Reviews
Modern, Safe & Agile C++
+41 79 432 23 32

SG12 list run by sg12-owner@lists.isocpp.org