[PATCH] D24289: Add warning when assigning enums to bitfields without an explicit unsigned underlying type

Arthur O'Dwyer via cfe-commits cfe-commits at lists.llvm.org
Thu Nov 17 18:59:21 PST 2016


On Thu, Nov 17, 2016 at 2:14 PM, Sasha Bermeister <sashab at chromium.org>
wrote:

> Although I agree with your philosophical discussion and suggestions, the
> reality is that MSVC's behavior is not a bug and compilers are free to
> interpret enum bitfields with no explicit underlying type in any way they
> want (see spec reference in GCC bug link), with a signed interpretation
> being a valid one. I'd say it's undefined behavior in C/C++ to store an
> enum in a bitfield without specifying an underlying type, since the
> compiler is free to interpret this bitfield in any way it wants -- in
> general, if you haven't specified an underlying type you should probably be
> warned when trying to store it in a bitfield because the compiler may not
> do what you expect.
>

Incorrect. The following program has perfectly well defined behavior:

enum E { e = 0 };
struct S { E bf : 4; } s;
int main() { s.bf = e; }

No compiler in the world should produce a warning on the above program.

Also, once you've got a struct type containing an offending bit-field, *any*
use of that bit-field is subject to the implementation-defined behavior you
noticed on MSVC. It's not just limited to assignment-expressions of
constants. That's why it's important to produce a warning on the
*declaration* of the bit-field, not on each subsequent expression that
refers to that bit-field.

enum E2 { e = 0, f = 1, g = 2, h = 3 };
struct S2 { E2 bf : 2; } s;  // this line should trigger a diagnostic
int main() { s.bf = e; }

Also, the current patch's diagnostic wording suggests to "consider giving
the enum E an unsigned underlying type", which would be very bad advice in
this situation (because it only works in C++11, and because it triggers a
GCC bug, and because it has non-local effects on the program's semantics).
The correct advice is to "consider giving the bit-field bf a width of 3
bits instead of 2."

HTH,
–Arthur
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20161117/8aa8ed23/attachment.html>


More information about the cfe-commits mailing list