Search code examples
cenumsbit-fields

Forcing enum field to 8 bits in standard C with bitfields


I saw few questions here about how to force an enum to 8 or 16 bits. The common answer was that it can be done in C++11 or higher. Unfortunately, I don't have that luxury.

So, here is what I'm thinking. I only need the enum to be 8 bits when it's in a struct whose size I want to minimize. So:

Option A:

typedef enum { A, B, C, MAX = 0xFF } my_enum;

struct my_compact_struct
{
    my_enum field1 : 8; // Forcing field to be 8 bits 
    uint8_t something;
    uint16_t something_else;
};

I think most or all optimizers should be smart enough to handle the 8 bitfield efficiently.

Option B:

Not use an enum. Use typedef and constants instead.

typedef uint8_t my_type;

static const my_type A = 0;
static const my_type B = 1;
static const my_type C = 2;

struct my_compact_struct
{
    my_type field1; 
    uint8_t something;
    uint16_t something_else;
};

Option A is currently implemented and seems to be working, but since I want to do (now and in the future) what's correct now and not just what's working, I was wondering if option B is clearly better.

Thanks,


Solution

  • If your specific values in an enum can fit into a smaller type than an int, then a C implementation is free to choose the underlying type of the enum to be a smaller type than an int (but the type of the enum constants in this case will be int). But there is no way you can force a C compiler to use a type smaller than an int. So with this in mind and the fact that an int is at least 16 bits, you're out of luck.

    But enums in C are little more than debugging aids. Just use an uint8_t type if you compiler has it:

    static const uint8_t something = /*some value*/
    

    If not then use a char and hope that CHAR_BIT is 8.