Step 1 of 7
enum class
An enumeration gives names to a small fixed set of choices: directions, days, game states. C has enum, but its names leak into the surrounding scope and silently turn into int, so the compiler happily compares a Color with a Weekday. C++'s scoped enum, enum class, fixes both problems.
#include <iostream>
#include <string>
enum class Light { Red, Yellow, Green };
std::string name(Light l) {
switch (l) {
case Light::Red: return "red";
case Light::Yellow: return "yellow";
case Light::Green: return "green";
}
return "?"; // unreachable for valid values, but keeps every path returning
}
Light next(Light l) {
switch (l) {
case Light::Red: return Light::Green;
case Light::Green: return Light::Yellow;
case Light::Yellow: return Light::Red;
}
return Light::Red;
}
int main() {
Light l = Light::Red;
for (int i = 0; i < 4; i++) {
std::cout << name(l) << " ";
l = next(l);
}
std::cout << "\n" << static_cast<int>(Light::Green) << "\n";
}
red green yellow red
2
How it works
- The values must be written with their type:
Light::Red, never justRed. So two enums can both have aRedwithout clashing. - There's no implicit conversion to
int.int n = l;is a compile error. When you really need the number, say so withstatic_cast<int>(l). The values count from 0 in the order written. switchpairs naturally with enums. Leave out thedefault:case: then-Wallwarns (-Wswitch) if some value isn't handled, which catches bugs when someone adds a new value later.- The final
returnafter the switch keeps the compiler happy that every path returns something, since an enum variable could in theory hold an out-of-range number.
Common mistakes
- Forgetting
returnorbreakin a case, so it falls through into the next one. - Adding a
default:that hides missing cases from the compiler's warning.
Your turn: write std::string to_string(Weapon w) covering every value, and int price(Weapon w): rifle 2700, sniper 4750, pistol 300.