How Big Is An Enum?

Enums are a great way to put descriptive names on "magic numbers", unexplained values that litter code and really should be avoided.

But how big is an enum? The answer is the standard computer answer: it depends.

The C standard specifies that enums are integers, but it does not specify the size. Once again, that is up to the people who write the compiler. On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less.

The GCC C compiler will allocate enough memory for an enum to hold any of the values that you have declared. So, if your code only uses values below 256, your enum should be 8 bits wide.

If you have even one value that is greater than 255, C will make the enum larger than 8 bits; big enough to hold the biggest number in the enum.

I actually used this recently. The controller I’m working on needed to exchange an enum with a PC as a part of the configuration process. For convenience we made everything 32-bits wide, but my enum looked like this:

typedef enum {
    CAN_250000_BAUD = 0,
    CAN_500000_BAUD = 1,
    CAN_1000000_BAUD = 2,
} CAN_BAUD_T;

And since this enum only takes the values 0, 1, or 2, C only allocates 1 byte. To force C to pad the value out to 32-bits, I just threw in an extra value

    CAN_BAUD_ZILLION = 100000

Since the value 100,000 takes 17 bits to represent, C will allocate a full 32-bits. You may also be able to set this with a compiler option, but then it will be applied to all enums instead of just this one.

In normal use you really don’t have to worry about the size of your enums, they will be big enough to do what you want. But when putting them into message to be sent to another system, you should remember that they can change size and may not be what you are expecting. If you store enums in non-volatile memory or on disk, be sure to review any code that might need to be updated when the size changes.

You can check the size of your enum by using:

sizeof(CAN_BAUD_T)

Just to make sure.


This post is part of a series. Please see the other posts here.


 The RTEMS ARM BSP exception table as an enum with size forcing entry.

The RTEMS ARM BSP exception table as an enum with size forcing entry.