Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 135 ยท Structures and Unions

Enumerations

Learn C enumerations - enum constants and their values, enums in switch, name tables, bit flags, sizeof, and C23 enums with a fixed underlying type.

Many values in a program come from a short, fixed list: the state of a traffic light, the direction a player faces, the level of a log message, the result of an operation. You could store them as plain numbers, 0 for red, 1 for yellow, 2 for green, but then every reader has to remember what 2 means, and nothing tells the compiler which numbers make sense. An enumeration (enum) gives each value in the list a name.

C's enums are deliberately simple: the names are integer constants, and an enum variable is an integer underneath. That makes them cheap and easy to mix with other code, but it also means C checks very little for you. This lesson shows how enums work, how to use them well in switch statements and lookup tables, how to build bit flags, and what C23 adds with enums that have a fixed underlying type.

Declaring an enum

An enum declaration lists names called enumerators. The first one is 0 unless you say otherwise, and each following one is one more than the one before it:

C A first enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

A few things to notice:

  • enum light is the type name, and light on its own is a tag, just like a struct tag. To declare a variable you write enum light now;. (A typedef removes the need for the enum keyword; more on that below.)
  • The enumerators LIGHT_RED, LIGHT_YELLOW and LIGHT_GREEN are constants of type int. You print them with %d and use them almost anywhere an integer constant is allowed: array sizes, case labels, static initializers. (The one exception is #if: the preprocessor runs before enums exist, so it treats every enumerator as an unknown name with the value 0.)
  • Enumerator names live in the ordinary scope, not inside the enum. Writing LIGHT_RED is enough; there is no light.RED or light::RED in C. That's why C programmers prefix enumerators with the type's name: two enums in the same file can't both have a RED.

Compared with a list of #define constants (see Constants), an enum groups related names, numbers them automatically, and its constants are real identifiers that a debugger can show by name.

Choosing the values

You can give any enumerator an explicit value. Enumerators without one continue counting from the previous value, and two enumerators may even share a value:

C Explicit enumerator values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The trailing comma after the last enumerator is allowed since C99 and makes adding new lines cleaner in version control. Values may be negative, and later enumerators may refer to earlier ones (LEVEL_DEFAULT = LEVEL_NORMAL).

How big is an enum variable? The standard says each enum type is compatible with some integer type that can hold all its values, chosen by the compiler. GCC and Clang pick unsigned int when no value is negative and int otherwise, so sizeof is 4 here, but don't depend on that in files or network formats. If the exact size matters, store the value in a fixed-width integer such as uint8_t (see Integer Types) or use C23's fixed underlying type, shown later in this lesson.

Note: Before C23, every enumerator value had to fit in an int. C23 relaxed this: an enumerator like BIG = 0x100000000 is allowed, and then the enumerator's type is wider than int. Keep values in the int range if your code must build with older compilers.

Enums are just integers in C

C does not protect an enum type. You can assign any integer to an enum variable, do arithmetic with enumerators, and compare enumerators from different enums. None of this is an error:

C
enum light now = 7;                 /* compiles: 7 is not a valid light */
int next = LIGHT_RED + 1;           /* compiles: plain int arithmetic */
now = HTTP_OK;                      /* compiles: wrong enum, only a warning */

Only the last line gets any attention, and only a warning: -Wextra turns on -Wenum-conversion, which reports implicit conversion from 'enum http_status' to 'enum light'. Storing 7 gets no warning at all. This is a major difference from C++, where an int never converts to an enum by itself and enum class blocks the reverse direction too (C and C++ compares the two languages). In C the enum type is documentation plus a few warnings. Your code has to validate values that come from outside: user input, files, or a function that returns int.

A popular trick makes validation easy: add a final enumerator that counts the others.

C
enum shape { SHAPE_CIRCLE, SHAPE_SQUARE, SHAPE_TRIANGLE, SHAPE_COUNT };

bool is_valid_shape(int value) {
    return value >= 0 && value < SHAPE_COUNT;
}

Because counting starts at 0 and goes up by one, SHAPE_COUNT is always the number of real shapes, even after you add new ones before it. You'll use it again for lookup tables.

Enums in switch statements

Enums and switch statements are made for each other. Better still, GCC and Clang know which enumerators exist. With -Wall (which our editor uses), a switch on an enum that misses an enumerator and has no default produces a warning. Run this example and read the warning above the output:

C switch on an enum (with a warning)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

GCC reports warning: enumeration value 'DIR_WEST' not handled in switch [-Wswitch], and the output confirms the bug: facing west, the function returns "?". Add a case DIR_WEST: return "north"; and the warning disappears.

This is why many C style guides say: when you switch on an enum, list every enumerator and leave out default. Then, when someone adds DIR_UP next year, the compiler points to every switch that needs updating. Handle impossible values after the switch (as the return "?"; does here), not with a default that silences the warning.

The loop also shows that d++ works on an enum variable, because it's an integer. That only makes sense when the values are consecutive, as they are here.

Turning enums into text

C has no built-in way to print an enumerator's name. The cleanest approach is an array of strings indexed by the enum, built with designated initializers so each name sits next to its enumerator:

C Names table with designated initializers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Sizing the array with LOG_LEVEL_COUNT keeps the table and the enum in step: if someone adds a level and forgets its name, the slot is NULL (unlisted elements of a static array are zero), and level_name returns "UNKNOWN" instead of crashing. The range check protects against values that were never valid in the first place.

Large projects sometimes generate the enum and the table from one list with a macro technique called X-macros; you'll see the idea in Macros.

typedef with enums

Writing enum log_level everywhere is wordy, so code often adds a typedef (see typedef):

C
typedef enum {
    COLOR_RED,
    COLOR_GREEN,
    COLOR_BLUE,
} color;

color favorite = COLOR_GREEN;       /* no 'enum' keyword needed */

Both styles are common. The Linux kernel prefers plain enum name, so the reader always sees that it's an enum; many libraries prefer the typedef. Pick one per project and stay consistent.

Enum flags

Sometimes values combine: a file can be readable and writable, a text style can be bold and underlined. Give each enumerator its own bit (a power of two), then combine them with | and test them with & from Bitwise Operators:

C Combining flags with bitwise operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice that the combined value is stored in an unsigned, not an enum style. STYLE_BOLD | STYLE_UNDERLINE is 5, which isn't one of the listed enumerators, so storing it in the enum type would be misleading (C allows it, but readers and debuggers expect a single listed value). The enum names the bits; an unsigned integer holds the set. Writing the values as 1 << n makes it obvious that each one is a separate bit. If you need many flags packed into a struct, Bit-Fields, the next lesson, offer another approach.

C23: enums with a fixed underlying type

C23 lets you choose the integer type behind an enum, with the same syntax C++ uses:

C C23 fixed underlying type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

With : unsigned char, every enum suit is exactly one byte, so a struct card takes two bytes instead of eight. With : uint64_t, enumerators can be as large as that type allows (the digit separators in 10'000'000'000 are also C23; see Integer Types). The compiler rejects an enumerator that doesn't fit the chosen type, which is a real safety gain for formats with an exact byte layout.

A fixed underlying type needs a C23 compiler: GCC 13+, Clang 20+ (Clang accepted it earlier as an extension). For code that must also build as C17, store the value in a fixed-width integer field and keep the enum for the names.

Common mistakes

  • Expecting type safety. enum light now = 42; compiles. Validate values from outside the program against a COUNT enumerator or a switch.
  • Name clashes. Enumerators share one scope with variables and functions, so enum color { RED }; and enum alert { RED }; in one file is an error. Prefix every enumerator.
  • Using default out of habit. It hides the -Wswitch warning that tells you about a forgotten case.
  • Writing enums to files as-is. sizeof an enum depends on the compiler (before C23). Convert to a fixed-width integer before saving it in a binary file.
  • Assuming consecutive values. Loops like for (d = FIRST; d <= LAST; d++) and lookup tables only work when there are no gaps.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given enum fruit { APPLE = 3, PEAR, PLUM = 10, FIG };, what are PEAR and FIG?

    An enumerator without a value is one more than the previous one, so PEAR follows APPLE (3) and FIG follows PLUM (10).
  2. 2. What happens when you compile enum light now = 42; in C?

    In C, enums are integer types and the compiler accepts any integer value. That's why values from outside the program must be validated.
  3. 3. A switch on an enum lists three of its four enumerators and has no default. What does GCC with -Wall do?

    -Wswitch (part of -Wall) warns about missing enumerators when there's no default, which is why style guides recommend listing every case instead.
  4. 4. Why is a combination like STYLE_BOLD | STYLE_ITALIC usually stored in an unsigned rather than in enum style?

    The enum names the individual bits. A combination is a set of bits that usually matches no single enumerator, so an unsigned integer describes it more honestly.
  5. 5. What does C23's enum suit : unsigned char { ... } change?

    A fixed underlying type makes the enum type's size and range exact, so sizeof(enum suit) is 1 and enumerators that don't fit are rejected.

Summary

  • enum name { A, B, C }; creates integer constants numbered from 0; explicit values reset the counting.
  • Enumerators are int constants in the surrounding scope: prefix them with the type name to avoid clashes.
  • C doesn't enforce enum types: any integer can be stored. Add a COUNT enumerator to validate ranges and size tables.
  • Switch on enums without default so -Wswitch reports forgotten cases.
  • Map enums to text with a designated-initializer array indexed by the enum.
  • Flags use power-of-two values combined with |, tested with &, and stored in an unsigned integer.
  • C23 adds a fixed underlying type (enum e : uint8_t) for exact sizes; before that, the size is the compiler's choice.

Next: Bit-Fields