Topics / C Programming / Q24
What is an enum and how big is it?
Short answer: An enum defines a set of named integer constants. In C the constants have type int, but the size of the enum type is implementation-defined: it must be able to hold all its values, and most compilers use int (4 bytes). Options such as -fshort-enums (the default in some Arm bare-metal ABIs and toolchains) make it the smallest type that fits, often 1 byte.
enum state { IDLE, RUN, ERROR = 10, SHUTDOWN }; /* 0, 1, 10, 11 */
enum state s = RUN;
Why use enums instead of #define
- They are typed integer constant expressions (usable as array sizes and
caselabels). - Debuggers show names instead of numbers.
- Compilers warn about unhandled cases in a
switchwithout adefault(-Wswitch). - Values are assigned automatically and stay consistent when items are added.
Pitfalls
- Size differs between builds: a struct containing an
enumcan have a different layout if one library was built with-fshort-enumsand another without; the linker cannot detect this. For structs that cross a module, ABI, file or network boundary, store a fixed-width integer (uint8_t state;) and convert. - C does not enforce enum ranges:
enum state s = 42;compiles. Validate values that come from outside (a received message). - Enum constants are
int; values larger thanINT_MAXwere not allowed before C23.
C23 improvements: you can fix the underlying type: enum state : uint8_t { IDLE, RUN };, which makes the size explicit and portable.
Useful patterns: a final STATE_COUNT member to size lookup tables (const char *names[STATE_COUNT]), and X-macros to generate the enum and its string names from one list.