Enums
Declaration, values, enum-as-int, and how enums show up in kernel-style code.
The shortest chapter — four pieces — and mostly about naming integers so the code reads like English instead of a table of magic numbers.
Declaration and values
enum color { RED, GREEN, BLUE }; /* RED=0, GREEN=1, BLUE=2 by default */
enum status {
STATUS_OK = 0,
STATUS_ERROR = -1,
STATUS_PENDING = 1
};Unless given explicit values, enum members auto-increment starting from 0. Giving them explicit values, like the status codes above, is common when the numbers themselves carry meaning — a return code an external caller has to check, for instance.
An enum is still just an int
enum color c = RED;
int n = c; /* fine — implicit conversion, no cast needed */
if (c == 0) { } /* also fine — RED literally is 0 */There's no real type safety here — an enum color is a named int underneath, and C will happily compare it against a raw integer or assign it into one. The benefit is entirely readability, not enforcement.
Where this shows up in kernel code
enum irqreturn is the pattern I now watch for — interrupt handlers return IRQ_HANDLED or IRQ_NONE instead of a bare 0 or 1, so the call site reads as intent instead of a number that means nothing without checking a header file.
Notes from readers
Comments — via GitHub