C++ Logo

sg12

Advanced search

Re: [SG12] [isocpp-core] New Issue?: [class.bit] p.4 - silent UB and necessary restriction?

From: Jens Maurer <Jens.Maurer_at_[hidden]>
Date: Fri, 5 Feb 2021 15:54:52 +0100
On 05/02/2021 13.35, Peter Sommerlad (C++) via Core wrote:
> Hi
>
> 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.

That doesn't follow. It just means that, if the precondition
is violated, the original value and the value of the bit-field
might not compare equal. That, of course, is far from
undefined behavior.

> 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.

This is only talking about enumerations for bit-fields.

Yes, it seems to say that for an enumeration, you should make
your bit-field large enough to handle the entire size of the
enumeration.
So, if you have a specified underlying type for the enumeration,
you might need to invest more bits than if you had left
the choice of underlying type to the compiler.

We could make the "compare equal" sentence a bit more useful
if we said that the bit-field just needs to be wide enough
to hold the particular value that was stored, not all values.

Jens

Received on 2021-02-05 08:54:59