Structs & Data Structures · beginner · ~8 min

enums

Name small integer constants.

Lesson

enum introduces a set of named integer constants. By default the first is 0 and each next is one more, but you can pin values: enum colour { red=1, green=2, blue=4 };.

Use enums for state machines, message kinds, error codes — anything that should be a small set of named ints. Combine with switch for exhaustiveness warnings.

Code examples

typedef enum { STATE_IDLE, STATE_RUNNING, STATE_DONE } state_t;
state_t s = STATE_IDLE;

Common mistakes

  • Underestimating: an enum value's type is implementation-defined (usually int). Don't assume a particular size when packing into a struct.