TExcelTAD
Home › C › C Enums

C Enums

An enumeration (enum) is a type made of a fixed set of named integer constants. Whenever a value can only be one of a few possibilities — a traffic light colour, a weekday, the state of a download — an enum lets you write those possibilities as readable names instead of "magic numbers".

Defining an enum

c · try it yourself
#include <stdio.h>

enum Level {
    LOW,
    MEDIUM,
    HIGH
};

int main(void) {
    enum Level fan = MEDIUM;
    printf("fan level = %d\n", fan);
    printf("LOW=%d MEDIUM=%d HIGH=%d\n", LOW, MEDIUM, HIGH);
    return 0;
}
fan level = 1
LOW=0 MEDIUM=1 HIGH=2

By default the first name is 0, and each following name is one more than the previous. The names (called enumerators) are constants of type int, so printing one with %d shows its number.

Choosing your own values

You can assign values explicitly. Names without a value continue counting from the previous one:

c · try it yourself
#include <stdio.h>

enum HttpStatus {
    OK = 200,
    CREATED,               // 201
    NOT_FOUND = 404,
    SERVER_ERROR = 500
};

enum Month { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };

int main(void) {
    printf("OK=%d CREATED=%d NOT_FOUND=%d SERVER_ERROR=%d\n",
           OK, CREATED, NOT_FOUND, SERVER_ERROR);
    printf("JUN is month %d, DEC is month %d\n", JUN, DEC);
    return 0;
}
OK=200 CREATED=201 NOT_FOUND=404 SERVER_ERROR=500
JUN is month 6, DEC is month 12

Two enumerators may even share the same value, though that is rarely useful.

Enums and switch

Enums and switch are a perfect pair. Each case names a state, which reads almost like a description of the logic:

c · try it yourself
#include <stdio.h>

typedef enum {
    RED,
    RED_AMBER,
    GREEN,
    AMBER
} Light;

Light next(Light current) {
    switch (current) {
        case RED:       return RED_AMBER;
        case RED_AMBER: return GREEN;
        case GREEN:     return AMBER;
        case AMBER:     return RED;
    }
    return RED;   // not reached, keeps the compiler happy
}

const char *light_name(Light l) {
    switch (l) {
        case RED:       return "red";
        case RED_AMBER: return "red+amber";
        case GREEN:     return "green";
        case AMBER:     return "amber";
    }
    return "?";
}

int main(void) {
    Light l = RED;
    for (int i = 0; i < 5; i++) {
        printf("%s\n", light_name(l));
        l = next(l);
    }
    return 0;
}
red
red+amber
green
amber
red

Tip: When you switch on an enum without a default case, GCC (-Wall) warns if you forget one of the enumerators. That is a great way to catch a missing case after adding a new value to the enum.

Using enums as array indexes

Because enumerators count up from 0, they make natural array indexes. Adding a final "count" enumerator gives you the number of values for free:

c · try it yourself
#include <stdio.h>

enum Weekday { MON, TUE, WED, THU, FRI, SAT, SUN, WEEKDAY_COUNT };

int main(void) {
    const char *names[WEEKDAY_COUNT] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
    int steps[WEEKDAY_COUNT] = {8200, 6400, 10100, 7300, 5600, 12800, 9900};

    int weekend = steps[SAT] + steps[SUN];
    printf("Weekend steps: %d\n", weekend);

    for (enum Weekday d = MON; d < WEEKDAY_COUNT; d++) {
        if (steps[d] >= 10000) {
            printf("%s: goal reached (%d)\n", names[d], steps[d]);
        }
    }
    return 0;
}
Weekend steps: 22700
Wed: goal reached (10100)
Sat: goal reached (12800)

Flags with powers of two

Giving enumerators values that are powers of two lets you combine several of them in one integer using bitwise OR (see C Bitwise Operators):

c · try it yourself
#include <stdio.h>

enum Permission {
    PERM_READ  = 1,    // 001
    PERM_WRITE = 2,    // 010
    PERM_EXEC  = 4     // 100
};

int main(void) {
    int perms = PERM_READ | PERM_WRITE;
    printf("can read:  %s\n", (perms & PERM_READ)  ? "yes" : "no");
    printf("can write: %s\n", (perms & PERM_WRITE) ? "yes" : "no");
    printf("can exec:  %s\n", (perms & PERM_EXEC)  ? "yes" : "no");
    return 0;
}
can read:  yes
can write: yes
can exec:  no

Things to know about C enums

Fact Consequence
Enumerators are plain int constants they can be used anywhere an integer is allowed, including case labels and array sizes
No automatic name strings to print names you need your own table or switch (as above)
Weak type checking enum Level l = 42; compiles without error
Enumerators share one namespace two enums cannot both have a member called RED — prefixes like LIGHT_RED help

Test yourself

In enum Size { S, M, L };, what is the value of L?

  1. 1
  2. 2
  3. 3
  4. 'L'

In enum Code { A = 10, B, C = 20, D };, what is D?

  1. 11
  2. 12
  3. 21
  4. 3

Why is adding a final COUNT enumerator useful?

  1. It speeds up the switch
  2. Its value equals the number of preceding enumerators, handy for array sizes and loops
  3. It is required by the standard
  4. It prints the enum names