An enum in C defines a set of named integer constants: enum color { RED, GREEN, BLUE }; makes RED equal to 0, GREEN 1 and BLUE 2. You then declare variables with enum color c = GREEN; and use the names in switch statements, arrays and comparisons instead of bare numbers.
Enum in C: basic syntax
The general form is the keyword enum, an optional tag name, and a comma-separated list of enumerators in braces. Here is a complete program:
#include <stdio.h>
enum color { RED, GREEN, BLUE };
int main(void)
{
enum color c = GREEN;
printf("%d\n", c);
return 0;
}
Example output: 1. The variable c holds an integer, so printf prints it with %d. The tag color lives in C's tag namespace, which is why you must write enum color each time, not just color, unless you add a typedef (see below). The enumerators RED, GREEN and BLUE are ordinary identifiers in the enclosing scope. A trailing comma after the last enumerator is allowed since C99.
How enum values are assigned
Three rules decide every value, per the C language reference:
- An enumerator written with
= constant-expressiongets that value. - An enumerator without
=gets the previous enumerator's value plus one. - The first enumerator, if it has no
=, is zero.
Mixing the rules gives results that surprise people the first time:
enum Foo { A, B, C = 10, D, E = 1, F, G = F + C };
/* A=0, B=1, C=10, D=11, E=1, F=2, G=12 */
Notice that E = 1 repeats the value of B. That is legal; only the names have to be unique. Notice also that G uses earlier enumerators in its expression. The expression must be an integer constant expression, so you cannot use a variable.
A common use of explicit values is matching an external format, such as HTTP status codes or file-format tags:
enum http_status { HTTP_OK = 200, HTTP_NOT_FOUND = 404, HTTP_TEAPOT = 418 };
Use typedef to drop the enum keyword
Because the tag needs the enum keyword, many C programs wrap the declaration in a typedef:
typedef enum { MON, TUE, WED, THU, FRI, SAT, SUN } weekday;
weekday today = WED;
Here the enum has no tag at all, and weekday is the only name for the type. If you need the enum to refer to itself or to be forward-referenced from a struct, give it a tag too: typedef enum day { ... } weekday;. Note that C has no forward declarations of enums: enum color; on its own is an error, according to the language reference.
Enum with switch
An enum paired with switch is the pattern that makes enums worth using. Enumerators are integer constants, so they are valid case labels:
enum color { RED, GREEN, BLUE };
const char *describe(enum color c)
{
switch (c) {
case RED: return "red";
case GREEN: return "green";
case BLUE: return "blue";
}
return "unknown";
}
The return "unknown" after the switch is deliberate. Since an enum variable can hold any integer (see the next section), control can reach it. GCC helps you keep switches complete: -Wswitch, which -Wall turns on, warns when a switch on an enumerated type lacks a case for one of the enumerators. Adding a default label silences that warning. -Wswitch-enum warns even when a default is present. If you want the compiler to flag a forgotten case when you add a new enumerator later, leave out default and handle the stray value after the switch, as above.
Enums are integers, not a checked type
C treats an enumerated type as an integer type. The language reference shows that you can assign a double to an enum variable and the value converts:
enum { ONE = 1, TWO } e;
e = 1.2; /* conversion: e is now ONE */
e = e + 1; /* e is now TWO */
Nothing stops enum color c = 42; from compiling either, and 42 is not one of the named values. Treat the enum as a way to name things and document intent, not as a guard. If a value comes from outside your program (a file, a network packet, user input), check that it is in range before using it as an enum.
Size and type of an enum
Without a fixed underlying type, the enumerated type is compatible with char, a signed integer type or an unsigned integer type. Which one is implementation-defined, but it must be able to hold every enumerator value. So sizeof(enum color) can differ between compilers and targets. Print it with %zu on your own toolchain if you need to know, and do not write it into a binary file or struct layout shared with other programs.
The enumeration constants themselves are different: before C23, each one has type int, and every value must be representable as an int.
What C23 changes
C23 adds two things. First, you can fix the underlying type:
enum small : unsigned char { LOW, MID, HIGH };
With a fixed underlying type, the enumerated type is compatible with that type, so its size is no longer a guess, and the enumerators have the enumerated type rather than int. Second, enumerator values that do not fit in int are no longer an error: the constant gets a larger signed or unsigned type instead. The fixed-type syntax needs a compiler with C23 support, so check your compiler's documentation and language mode flag before relying on it. In older modes such as C11, it is a syntax error.
Enum as bit flags
Give each enumerator its own bit and combine them with the bitwise OR operator. The bitwise operators article covers the operators in detail.
enum perm {
PERM_READ = 1 << 0, /* 1 */
PERM_WRITE = 1 << 1, /* 2 */
PERM_EXEC = 1 << 2 /* 4 */
};
unsigned flags = PERM_READ | PERM_WRITE; /* 3 */
if (flags & PERM_WRITE) {
/* write bit is set */
}
flags &= ~PERM_WRITE; /* clear the write bit */
Store combined flags in an unsigned variable rather than in the enum type. A value like 3 is not one of the named enumerators, and GCC's -Wswitch handling treats case labels that do not match enumerators specially, unless the enum carries the flag_enum attribute.
Print the name of an enum value
C keeps no names at run time, so printf("%d", c) shows only the number. Build a lookup table with designated initializers (C99 and later), which keeps each string tied to its constant even if you reorder the enum:
static const char *const color_names[] = {
[RED] = "red",
[GREEN] = "green",
[BLUE] = "blue",
};
printf("%s\n", color_names[GREEN]); /* green */
Check the index is within the array before indexing, since an enum variable can hold values with no entry. Add a final count constant if you want a bounds check that updates itself: put COLOR_COUNT as the last enumerator, and it equals the number of real values as long as you have not assigned explicit values.
Enum or #define?
Both give you named constants. The language reference lists the reasons to prefer an enum: the names are visible in a debugger, they obey scope rules, and they take part in the type system. A #define is textual substitution with none of that. The one thing an enum cannot do (before C23) is hold a value that does not fit in int, or a non-integer value such as a floating-point or string constant. Use #define or a const object for those.
Common mistakes
- Reusing a name. Enumerators share the ordinary namespace with variables and functions, so two enums that both define
REDin the same scope fail to compile. Prefix the names (COLOR_RED,LIGHT_RED). - Forgetting
enumin the declaration. Writingcolor c;when you declaredenum colorgives an error like "unknown type name". Add the keyword or a typedef. - Assuming the first value is 1. It is 0. If 0 means "not set" in your data, either start the enum at 1 explicitly or reserve a first enumerator such as
COLOR_NONE. - Relying on enum size in structs written to disk. The size is implementation-defined before C23's fixed types. Store a fixed-width integer type such as
uint8_tinstead and convert.
If you are also working with compound types, struct in C shows how to keep an enum field next to the data it describes. One scoping detail from the language reference: an enum declared inside a struct is not scoped to that struct in C, so its tag and constants remain visible afterwards in the enclosing scope.
Frequently asked questions
- Is an enum in C type safe?
- No. An enumerated type is an integer type, so C lets you assign any integer to an enum variable and mix enum values in arithmetic without an error. A compiler can warn about some misuse, for example GCC's -Wswitch warns when a switch on an enum lacks a case for one of its constants, but the language itself does not stop you.
- What is the default value of the first enum constant in C?
- Zero. If an enumerator has no = value, it gets the previous enumerator's value plus one, and the first enumerator with no = value is 0. So enum { A, B, C } gives A = 0, B = 1, C = 2.
- Can two enum constants have the same value?
- Yes. C allows duplicate values, either by writing the same number twice or by resetting the counter with an explicit value. The names must still be unique in their scope. Duplicates are handy for aliases, such as a LAST constant equal to the final real value.
- How do I print the name of an enum value in C?
- C has no built-in way to get an enumerator's name at run time. The usual approach is an array of strings indexed by the enum value, using designated initializers so each string sits next to its constant. printf with %d prints only the number.