Enumerations (enum) in C define custom data types containing sets of named integer constants, replacing magic numbers with readable state machine labels.

C Enum State Machine Code Example

enum_state.cc
#include <stdio.h>
 
typedef enum {
    STATE_IDLE = 0,
    STATE_CONNECTING = 1,
    STATE_CONNECTED = 2,
    STATE_ERROR = -1
} ConnectionState;
 
void handle_state(ConnectionState state) {
    switch (state) {
        case STATE_IDLE:       printf("Status: Idle\n"); break;
        case STATE_CONNECTING: printf("Status: Connecting...\n"); break;
        case STATE_CONNECTED:  printf("Status: Connected\n"); break;
        case STATE_ERROR:      printf("Status: Connection Error!\n"); break;
    }
}
 
int main(void) {
    ConnectionState current = STATE_CONNECTING;
    handle_state(current);
    return 0;
}