Thuta Learning
C
AdvancedProgrammingBeginner

Enums

CLesson 3025 min

What you'll walk away with

  • Declare an enum and predict each constant's value, including explicit values
  • Explain that enum constants are ints and that an enum variable can still hold undeclared values
  • Use switch over an enum so that -Wswitch catches missing cases
  • Write a validating parse function and a to-string function for an enum

Explain it simply

Explain it simply

An enum (enumeration) is a type that lists a fixed set of named choices. Instead of remembering that 0 means low, 1 means medium and 2 means high, you write enum Level { LOW, MEDIUM, HIGH }; and use the names. The computer still stores small whole numbers; the names are for the people who read and maintain the code.

Enums fit anything that is one item from a short list: the status of an order, the direction a game character faces, the day of the week, a menu choice. When you see a variable of type enum OrderStatus, you know at once which values make sense for it.

Problem → Why → Solution

The problem: magic numbers say nothing

Order-processing code written with bare numbers works on the day it is written. Six months later nobody remembers whether status 2 means paid or shipped, a new status is given the number 2 by mistake, and a typo such as status == 22 compiles without complaint. The code below is correct, but you cannot tell that by reading it, and passing it 9 prints nothing at all.

order_status.c
#include <stdio.h>

void describe(int status) {
    if (status == 1) {
        printf("waiting for payment\n");
    } else if (status == 2) {
        printf("ready to ship\n");
    } else if (status == 3) {
        printf("on its way\n");
    }
    /* what about 9? nobody remembers that it means cancelled */
}

int main(void) {
    describe(2);
    describe(9);   /* prints nothing at all */
    return 0;
}

Why are bare numbers risky?

Bare numbers carry no meaning, so the knowledge of what 1, 2 and 3 stand for lives only in people's heads or in comments that drift out of date. The compiler cannot help, because every int is as valid as any other. An enum gives each value a name and a type: the code reads like the business rule, a switch over the enum lets GCC point out forgotten cases, and changing a value happens in exactly one place.

Core concept: named integer constants

enum Level { LOW, MEDIUM, HIGH }; declares two things at once: a new type, enum Level, and three enumeration constants. Unless you say otherwise, the first constant is 0 and each following one is one more than the previous, so LOW is 0, MEDIUM is 1 and HIGH is 2. You can set any value explicitly: enum Color { RED, GREEN = 5, BLUE }; makes BLUE 6, because counting continues from the last explicit value. Two constants may even share a value.

In C17 every enumeration constant has type int, so it works anywhere an integer does: as an array index, in arithmetic, as a switch case label. The enum type itself is compatible with an integer type the compiler chooses (GCC uses unsigned int when no constant is negative and int otherwise), and sizeof(enum Level) is 4 with GCC on x86-64. Do not rely on that size in files or network messages; store an explicitly sized integer instead.

C does not stop an enum variable from holding other numbers. enum Level l = 42; compiles silently even with -Wall -Wextra, and a value read from a file or typed by a user can be anything. So treat an enum as a promise that you check yourself at the edges of the program: convert incoming integers with a validating function, and give every switch a way to handle unknown values.

Enumeration constants share one scope with variables and functions, so two enums in the same file cannot both have a constant called NONE; GCC reports redeclaration of enumerator 'NONE'. That is why C code prefixes constants with the type's name, as in ORDER_PENDING or LEVEL_HIGH. Ending the list with a LEVEL_COUNT constant is a common trick: it equals the number of real values and can size a table of names.

Mental model: a labelled set of choices
  1. List the choices: enum T { A, B, C }
  2. Names become ints: A=0, B=1, C=2
  3. Code compares names, not numbers
  4. Validate numbers arriving from outside

An enum documents which values make sense; it does not stop other integers from appearing.

General pattern

c
enum Name {
    NAME_FIRST,            /* 0 */
    NAME_SECOND,           /* 1 */
    NAME_LATER = 10,       /* explicit value */
    NAME_NEXT              /* 11 */
};

enum Name value = NAME_SECOND;
switch (value) {
case NAME_FIRST: /* ... */ break;
default:         /* unknown or unhandled values */ break;
}

Constants start at 0 and go up by one; an = value resets the count from that point. Declare a variable of the enum type and handle each constant in a switch.

Example: checking a level by name

This short program is the smallest useful enum: a type with three named levels and one comparison. Its value is in what the reader sees: current == MEDIUM explains itself, while current == 1 would need a comment. The deeper sections below grow it into the patterns real code uses: switch statements, name tables and a COUNT constant.

c
#include <stdio.h>

enum Level {
  LOW,
  MEDIUM,
  HIGH
};

int main() {
  enum Level current = MEDIUM;

  if (current == MEDIUM) {
    printf("Current level is medium.");
  }
  return 0;
}

Code breakdown

  1. Lines 3-7enum Level {

    This declares the type enum Level and three constants, LOW = 0, MEDIUM = 1 and HIGH = 2. The constant names are visible throughout the file, so larger projects would prefix them, as in LEVEL_LOW.

  2. Line 9int main() {

    In C17, () leaves the parameters unspecified; int main(void) is the precise way to say "no parameters" (in C23 the two forms mean the same).

  3. Line 10enum Level current = MEDIUM;

    A variable of type enum Level starts at MEDIUM. Memory holds the number 1, but the reader sees a level.

  4. Line 12if (current == MEDIUM) {

    The comparison reads like the requirement. To the compiler it is the same as comparing with 1, so the enum costs nothing at run time.

You should see
Current level is medium.

switch, -Wswitch and unknown values

When a switch over an enum has no default and misses a constant, -Wswitch (part of -Wall) warns: enumeration value 'HIGH' not handled in switch. That warning is valuable enough to shape a common style: in a function that converts an enum to text, list every constant, leave out default, and return a fallback after the switch for values outside the enum.

level_name.c
#include <stdio.h>

enum Level { LEVEL_LOW, LEVEL_MEDIUM, LEVEL_HIGH };

const char *level_name(enum Level level) {
    switch (level) {          /* no default: -Wswitch reports missing cases */
    case LEVEL_LOW:    return "low";
    case LEVEL_MEDIUM: return "medium";
    case LEVEL_HIGH:   return "high";
    }
    return "unknown";         /* values outside the enum end up here */
}

int main(void) {
    for (int raw = 0; raw <= 3; raw++) {
        printf("%d -> %s\n", raw, level_name((enum Level)raw));
    }
    return 0;
}

The output is 0 -> low, 1 -> medium, 2 -> high and 3 -> unknown. If someone later adds LEVEL_CRITICAL, the compiler points straight at level_name(). Had the switch contained default:, that warning would disappear and the new constant would quietly come back as "unknown".

Using a COUNT constant and enums as indexes

When the constants run consecutively from 0, they work as array indexes. The trailing DIR_COUNT keeps array sizes and loops in step with the enum.

directions.c
#include <stdio.h>

enum Direction { DIR_NORTH, DIR_EAST, DIR_SOUTH, DIR_WEST, DIR_COUNT };

static const char *const DIRECTION_NAMES[DIR_COUNT] = {
    "north", "east", "south", "west"
};

int main(void) {
    enum Direction moves[] = {DIR_NORTH, DIR_EAST, DIR_NORTH, DIR_WEST, DIR_NORTH};
    int counts[DIR_COUNT] = {0};

    for (size_t i = 0; i < sizeof moves / sizeof moves[0]; i++) {
        counts[moves[i]]++;
    }
    for (int d = 0; d < DIR_COUNT; d++) {
        printf("%-5s: %d\n", DIRECTION_NAMES[d], counts[d]);
    }
    return 0;
}

It prints north: 3, east: 1, south: 0 and west: 1. As long as a new direction is inserted before DIR_COUNT, the array sizes and loops stay correct. Indexing with the enum is safe here only because every value in moves came from the enum itself; a number from outside would need a range check first.

In real projects

Where this shows up in real projects

Enums are everywhere in C APIs. The C standard library itself uses plain macros for most constants, but large libraries lean on enums: Vulkan's VkResult lists success and error codes, and SDL uses enums for key codes and event types. Almost every embedded project describes the states of a state machine, such as IDLE, CONNECTING, CONNECTED and ERROR, as an enum driven by a switch.

When enum values cross a boundary, real projects pin them down. Values saved in a database or sent over a network get explicit numbers (ORDER_PAID = 2), so reordering the declaration cannot silently change stored data, and a parse function turns incoming integers or strings into the enum while rejecting anything unknown. A matching to-string function produces log lines like status=PAID instead of status=2, which keeps production logs readable.

Common mistakes

Common mistakes

1. Assuming an enum variable only holds declared values

enum Level l = 42; compiles without a warning, and so does casting any number read from input. Code that then indexes a name table with such a value reads outside the array. Validate integers where they enter the program and keep a fallback after every switch.

2. Reordering or inserting constants whose numbers are stored

If ORDER_PAID is implicitly 1 today and someone inserts ORDER_REVIEW before it, every PAID order already saved in a file is read back as REVIEW. Give explicit values to any enum whose numbers leave the program, and only append new constants at the end.

3. Reusing a constant name in two enums

enum Status { NONE, ACTIVE }; and enum Filter { NONE, ALL }; in one file fail with redeclaration of enumerator 'NONE'. Prefix constants with their type, as in STATUS_NONE and FILTER_NONE.

4. Adding a default that hides missing cases

A default label silences -Wswitch, so a newly added constant falls into the generic branch without any warning. In switches that should cover every constant, list them all and handle out-of-range values after the switch instead.

Best practices

Best practices

  • Prefix every constant with the enum's name in capitals to avoid clashes and make the type obvious.
  • Use explicit values for enums that are stored or transmitted, and never renumber them.
  • Pair important enums with a validating parse function and a to-string function.

Mini challenge

Mini challenge: order status codes

Turn codes read from an order file into an enum safely and print them by name.

  • Write enum OrderStatus with the explicit values ORDER_PENDING = 1, ORDER_PAID = 2, ORDER_SHIPPED = 3 and ORDER_CANCELLED = 9
  • const char *status_name(enum OrderStatus s) returns the name in capitals using a switch over every constant
  • int parse_status(int raw, enum OrderStatus *out) stores the status and returns 1 for a known code, and returns 0 otherwise
  • Process the codes {1, 3, 7, 9} and print either the name or invalid status code
order_codes.c
#include <stdio.h>

enum OrderStatus {
    // TODO: PENDING = 1, PAID = 2, SHIPPED = 3, CANCELLED = 9, with an ORDER_ prefix
};

const char *status_name(enum OrderStatus status) {
    // TODO: switch over every constant; return "UNKNOWN" after the switch
}

int parse_status(int raw, enum OrderStatus *out) {
    // TODO: accept only the four known codes, store through out, return 1
    // TODO: return 0 for anything else
}

int main(void) {
    int codes_from_file[] = {1, 3, 7, 9};
    // TODO: parse each code and print "1 -> PENDING" or "7 -> invalid status code"
    return 0;
}

Expected: The output should be: 1 -> PENDING 3 -> SHIPPED 7 -> invalid status code 9 -> CANCELLED

Show hint

In parse_status, switch (raw) can stack the four labels case ORDER_PENDING: case ORDER_PAID: ... and then do *out = (enum OrderStatus)raw; return 1;, with default: returning 0. In status_name, leave out default and return "UNKNOWN" after the switch.

Show solution
order_codes.c
#include <stdio.h>

enum OrderStatus {
    ORDER_PENDING = 1,
    ORDER_PAID = 2,
    ORDER_SHIPPED = 3,
    ORDER_CANCELLED = 9
};

const char *status_name(enum OrderStatus status) {
    switch (status) {
    case ORDER_PENDING:   return "PENDING";
    case ORDER_PAID:      return "PAID";
    case ORDER_SHIPPED:   return "SHIPPED";
    case ORDER_CANCELLED: return "CANCELLED";
    }
    return "UNKNOWN";
}

/* Returns 1 and stores the status when raw is a known code, else 0. */
int parse_status(int raw, enum OrderStatus *out) {
    switch (raw) {
    case ORDER_PENDING:
    case ORDER_PAID:
    case ORDER_SHIPPED:
    case ORDER_CANCELLED:
        *out = (enum OrderStatus)raw;
        return 1;
    default:
        return 0;
    }
}

int main(void) {
    int codes_from_file[] = {1, 3, 7, 9};

    for (int n = 0; n < 4; n++) {
        enum OrderStatus status;
        if (parse_status(codes_from_file[n], &status)) {
            printf("%d -> %s\n", codes_from_file[n], status_name(status));
        } else {
            printf("%d -> invalid status code\n", codes_from_file[n]);
        }
    }
    return 0;
}

Quick quiz 1 / 3

Given enum Color { RED, GREEN = 5, BLUE };, what is the value of BLUE?

Quick quiz 2 / 3

Level's constants are 0 to 2. What is true about enum Level l = 42; in C?

Quick quiz 3 / 3

A switch over enum Level handles only LOW and MEDIUM and has no default. What does gcc -Wall report?

What to remember

  • An enum declares a type plus named integer constants that count up from 0 unless you set values.
  • Enumeration constants are ints in C17; the enum's own size is the compiler's choice, so do not store it raw.
  • C allows any integer in an enum variable, so validate values that come from outside and handle unknown ones.
  • Prefix constants with the type name, and give explicit values to enums that are saved or transmitted.

GNU C compiler diagnostics — GNU Project

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Enums | Thuta Learning