The short answer
An enum gives names to a fixed set of values. The main purpose is clearer code. A name such as SHIPPED says more than the number 2, and the compiler can catch some mistakes that plain numbers would hide.
The problem with plain numbers
Here is a common way to store a status:
int status = 2; // what does 2 mean?
A reader has to guess what 2 means unless a comment explains it. With an enum, the code explains itself:
enum OrderStatus { PENDING, SHIPPED, DELIVERED };
OrderStatus status = SHIPPED;
Benefits of using an enum
Readable code
A name describes what the value means. status == SHIPPED is easier to read than status == 1, and it needs no comment.
Typos become compile errors
If you misspell SHIPPED as SHIPED, the compiler reports an undeclared identifier. A plain int set to a wrong number compiles without any warning.
Related values stay together
PENDING, SHIPPED, and DELIVERED belong to one type, so it is clear they describe the same thing.
Warnings in switch statements
switch (status) {
case PENDING:
// ...
break;
case SHIPPED:
// ...
break;
}
This switch doesn’t handle DELIVERED. With -Wall on GCC or Clang, the compiler warns about a missing enumerator in a switch that has no default. If you add a new name later, the warning points you to each switch that needs it.
Scoped enums avoid clashes
With enum class, the names live inside the enum, so you write OrderStatus::SHIPPED. Two enums can then use the same short names without conflict.
Limits to keep in mind
- An enum isn’t a full validation system. C and C++ accept any integer you cast to the type, so check values that come from outside your program.
- Enum values aren’t text. Printing a name takes extra code.
- An enum works best for a set that is fixed and known in advance. Values that keep growing, such as user IDs, need a different approach.
When an enum is a good fit
Use an enum for small, fixed sets such as order states, menu options, directions, or error codes. If you put the enum in a header file that several source files include, add a header guard so the definition isn’t repeated. Header guard in c shows how to write one.