Enums in C
Enums name a fixed set of integer constants: enum Day { MON, TUE, WED }; gives MON the value 0, TUE 1, and so on (overridable with = assignments). They replace magic numbers with compiler-checked labels in state machines, error codes, and option sets.
C enums are thin — enumerators leak into the enclosing scope and convert to int freely, so MON from two enums collides. Prefix names (COLOR_RED, ERR_TIMEOUT) to avoid clashes, assign explicit values for protocols, and treat enums as documentation the compiler lightly enforces.
Name the set
enum Day { MON, TUE, WED }; — MON is 0, TUE 1, WED 2 automatically; explicit = values override any of them.
Use in switches
switch (day) with case MON: reads as intent — and -Wswitch warns when an enumerator lacks its case.
Prefix everything
Enumerators share the enclosing scope — COLOR_RED vs ERR_OK prefixes prevent cross-enum collisions.
They're still ints
Enums convert to int implicitly (printf %d works); the checking is light — names plus switch warnings, not type walls.
#include <stdio.h> enum Traffic { RED, YELLOW, GREEN }; int main(void) { enum Traffic light = GREEN; if (light == GREEN) { printf("go\n"); } printf("%d\n", RED); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.