Sometimes a value can only be one of a few choices: a traffic light is red, yellow or green. Instead of using numbers like 0, 1 and 2 (and remembering what they mean), give the choices names with enum class:
#include <iostream>
using namespace std;
enum class Light { Red, Yellow, Green };
int main() {
Light now = Light::Red;
if (now == Light::Red) {
cout << "Stop!\n";
}
now = Light::Green;
if (now == Light::Green) {
cout << "Go!\n";
}
return 0;
}Output
Stop! Go!
Lightis a new type with exactly three possible values.- You write the values with the type name in front:
Light::Red. - You can't accidentally put any other value into a
Lightvariable.
enum and switch: a perfect pair
#include <iostream>
#include <string>
using namespace std;
enum class Level { Easy, Medium, Hard };
string describe(Level level) {
switch (level) {
case Level::Easy: return "Relaxed and fun";
case Level::Medium: return "A fair challenge";
case Level::Hard: return "Good luck!";
}
return "";
}
int main() {
cout << describe(Level::Medium) << "\n";
cout << describe(Level::Hard) << "\n";
return 0;
}Output
A fair challenge Good luck!
Getting the number behind a value
Each choice is stored as a number, starting at 0. To see it, use static_cast<int>:
#include <iostream>
using namespace std;
enum class Day { Mon, Tue, Wed, Thu, Fri };
int main() {
Day d = Day::Wed;
cout << static_cast<int>(d) << "\n";
return 0;
}Output
2
Remember: Older code uses plain
enum(withoutclass). It works, but its names leak out and mix with numbers too easily. Preferenum class.