Quentin Pope <> writes:
> Does the C standard say anything about using enum in a bit field? Like
>
> enum {
> apple,
> orange
>
> } fruit;
>
> struct {
> enum fruit f:16;
>
> };
Yes. C99 6.7.2.1p4:
A bit-field shall have a type that is a qualified or unqualified
version of _Bool, signed int, unsigned int, or some other
implementation-defined type.
This is a constraint, and "implementation-defined" means that the
ipmlementation must document any other types, so the compiler (in
conforming mode) must complain about an enum bit-field *unless*
the compiler's documentation specifically says that it's permitted.
More generally, using a bit field of a type other than the ones
listed in the standard makes your code non-portable. (Using bit
fields is likely to do that as well, if you're assuming that it
defines the layout precisely.)
[...]
> I think this is very useful and in our project we encourage people to use
> enum instead of #define to create constants. Although not used in a lot
> of places, the bit field somewhat defeats this purpose. Is there a
> rationale why this is so? Is there any way to shut up the compiler?
> I've checked the FAQ. No answers from there.
In the example you've shown us, making "f" a bit field doesn't make much
sense; it would be simpler to write just "enum fruit f;". Why do you
need f to be exactly 16 bits?
If your purpose is to define some constants, you can use enumerations
without necessarily using the enumeration type. For example:
enum { apple, orange };
struct basket { unsigned f:16; };
struct basket b;
b.f = apple;
Enumeration constants in C are not actually of the enumeration type;
they're always of type int.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"