C++ Enums
An enumeration is a type whose values are a fixed list of names: the days of the week, the levels of a game, the states of an order. C++ has two kinds; prefer enum class.
enum class
#include <iostream>
enum class Level { Low, Medium, High };
int main() {
Level fan = Level::Medium;
if (fan == Level::Medium) {
std::cout << "Medium speed\n";
}
std::cout << "Medium is number " << static_cast<int>(Level::Medium) << "\n";
return 0;
}Medium speed Medium is number 1
The names are written with the enum's name in front (Level::Medium), so two enums can both have a value called Low. An enum class value does not turn into a number by itself; static_cast<int> converts it when you need the number.
Choosing the values
#include <iostream>
enum class HttpStatus { Ok = 200, NotFound = 404, ServerError = 500 };
int main() {
HttpStatus s = HttpStatus::NotFound;
std::cout << static_cast<int>(s) << "\n";
return 0;
}404
Enums and switch
#include <iostream>
#include <string>
enum class Size { Small, Medium, Large };
int price(Size s) {
switch (s) {
case Size::Small: return 120;
case Size::Medium: return 150;
case Size::Large: return 180;
}
return 0;
}
std::string name(Size s) {
switch (s) {
case Size::Small: return "small";
case Size::Medium: return "medium";
case Size::Large: return "large";
}
return "?";
}
int main() {
Size order[] = {Size::Large, Size::Small, Size::Medium};
int total = 0;
for (Size s : order) {
std::cout << name(s) << ": " << price(s) << "\n";
total += price(s);
}
std::cout << "total: " << total << "\n";
return 0;
}large: 180 small: 120 medium: 150 total: 450
A switch over all values of an enum gets a warning when a value is forgotten, which helps when new values are added later.
The older plain enum
Without class, enum Color { Red, Green }; puts Red and Green directly into the surrounding scope and lets them convert to int silently. That is how C works and you will see it in older code, but the names can clash and mistakes slip through; enum class avoids both.
Why not just use numbers?
setSpeed(Level::High) explains itself; setSpeed(2) does not. With an enum class, a function that takes a Level cannot be called with a random number or with a value of another enum by mistake: the compiler stops it. Enums also make the set of possible values visible in one place, so a reader knows every case the code must handle.
Practice exercises
- Make an
enum class Seasonand print a sentence for each season with aswitch. - Make an
enum class Directionand a function that returns the opposite direction. - Try to print an
enum classvalue directly withcoutand read the error; fix it withstatic_cast.