10.1 — enum class: a set of named options
Read one box at a time. No rush.
Named choices#
Sometimes a value can only be one of a few options: a traffic light is red, yellow or green. An enum gives each option a name.
C++
enum class Light{ red, yellow, green,}; Light now { Light::red }; if (now == Light::red){ std::cout << "Stop!\n";}Why not just use numbers?#
if (light == 2) — what is 2? Nobody knows. if (light == Light::green) explains itself.
enum class + switch#
Enums and switch are a great team:
C++
void describe(Light l){ switch (l) { case Light::red: std::cout << "Stop\n"; break; case Light::yellow: std::cout << "Slow down\n"; break; case Light::green: std::cout << "Go\n"; break; }}Good habit
Use enum class (not plain enum). Its option names don't leak out and clash with other names, and it won't silently turn into a number.
Tip: press ← / → to move between lessons, / to search.