An Enum is a powerful tool for defining a variable that can only hold a specific set of values. While the compiler treats these values as integers behind the scenes, you interact with them using descriptive names. This prevents the use of "Magic Numbers"—unexplained numeric literals that make code difficult to debug.
The syntax for an enumeration starts with the enum keyword, followed by the name of the enumeration and a list of possible values enclosed in curly braces.
By default, the first name in an enum is assigned the value 0, the second is 1, and so on. Every subsequent name increases by 1.
LOW = 0MEDIUM = 1HIGH = 2You can override the default numbering at any point. If you assign a specific value to one member, the members following it will continue the increment from that new number.
One of the biggest misconceptions about Enums is that they store strings. They do not.
When the C compiler encounters an enum name like OK, it replaces it with the integer 200 during compilation. This means:
int (4 bytes on most systems).if (status == OK)) is just as fast as comparing two integers.
Enums and switch statements are a perfect match. They allow you to write logic that looks like plain English.
While you could use #define LOW 0, Enums are generally preferred in modern C for several reasons:
| Feature | Enum | #define |
|---|---|---|
| Type Safety | Enums are a distinct type, aiding in error checking. | Literal text replacement (no type). |
| Debugging | Visible in debuggers as names. | Often invisible to debuggers. |
| Grouping | Naturally groups related constants. | Requires manual grouping/naming. |
printf("%s", current_difficulty). It will print the integer 1, not the word "MEDIUM". To print the name, you must write a helper function with a switch case.enum Color { RED } and enum Fruit { RED } in the same scope, the compiler will throw an error because RED is defined twice.typedef to avoid writing the enum keyword repeatedly.COUNT at the end. Because COUNT will automatically be assigned a value equal to the number of members before it, you can use it to define array sizes or loop limits easily!