C Reference ยท Keywords and Statements
The enum keyword
Reference for C enum: named integer constants, explicit values, the underlying type, C23 fixed underlying types and common pitfalls.
An enum defines a set of named integer constants. By default the first constant is 0 and each following one is the previous plus one. You can assign explicit values to any of them. The constants are ordinary integer constant expressions, so they can be used in case labels, array sizes and static_assert.
C enumerations are weakly typed: an enumerated type is compatible with an integer type, and any integer can be assigned to it. The benefit is readability, not type safety.
enum color { RED, GREEN = 5, BLUE }; /* 0, 5, 6 */
Try it
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.
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.
Syntax
enum tag { name1, name2 = constant, name3, ... }; enum tag : underlying-type { ... }; /* C23 */ enum tag object;
| Part | Description |
|---|---|
tag |
Optional name. The type is enum tag. |
name = constant |
Explicit value; the next unnamed constant continues from it. |
: underlying-type |
C23: choose the integer type (for example uint8_t). Without it the type is implementation-defined but compatible with char or a signed/unsigned integer that fits all values. |
Returns: the constants have type int (before C23, always) or the enum's underlying type if a value does not fit in int or a type is fixed (C23).
Errors: two constants in the same scope cannot share a name. A trailing comma after the last constant is allowed since C99.
Usage notes
- Duplicate values are fine.
enum { A = 1, B = 1 };is legal, which is useful for aliases but breaksswitch(duplicatecase). - Constants live in the surrounding scope. Two enums in one scope cannot both define
RED. Use a prefix:COLOR_RED. - No range checking.
enum color c = 42;compiles. Use-Wswitchso GCC warns about missing cases, and avoiddefaultif you want that warning. - Counting trick. A final
COUNTconstant gives the number of entries when values are consecutive. - Bit flags. Use powers of two and combine with
|; the result is anint, not the enum type. - Size. The classic enum is usually the size of an
int; C23enum : typemakes it portable. - Enums vs
#define. Enum constants are visible to debuggers and obey scope; macros do not. boolpattern. In C23 use the built-inboolinstead ofenum { false, true }.