What an enum is
Enum is short for enumeration. An enum is a list of named values. Each name stands for a number, and the compiler assigns the numbers for you unless you choose them yourself.
A simple example
Here is a short C++ program with three traffic light states:
#include <iostream>
enum TrafficLight { RED_LIGHT, YELLOW_LIGHT, GREEN_LIGHT };
int main() {
TrafficLight light = YELLOW_LIGHT;
if (light == YELLOW_LIGHT) {
std::cout << "Slow down\n";
}
return 0;
}
The program prints Slow down. Here is what each part does:
enum TrafficLightdefines a type with three names.RED_LIGHTis 0,YELLOW_LIGHTis 1, andGREEN_LIGHTis 2, because numbering starts at 0.lightis a variable that holds one of those names.- The
ifcompareslightwith a name, so the code says what it checks.
Why names beat numbers
Compare these two lines:
if (light == 1) { /* ... */ }
if (light == YELLOW_LIGHT) { /* ... */ }
With an unscoped enum, both lines compile. The second one says what it checks, though. Anyone reading the code knows which state is being tested without looking up a table.
Things to keep in mind
- Names in the same scope must be unique.
- The numbers follow the order you wrote them in. If the exact numbers matter, set them yourself.
- A name isn’t text. Printing
YELLOW_LIGHTas a word takes extra code, such as an array of names. - To act on each state, a
switchis the usual tool. The rules are in switch case statement in c.