C++ Enums
An enum is a set of named whole-number values. A program uses the names in place of plain numbers.
Enum values print as numbers
Low, Medium, and High print as numbers. An enum value prints as its number, so the lines show 0, 1, and 2.
#include <iostream>
enum Level { Low, Medium, High };
int main() {
std::cout << Low << std::endl;
std::cout << Medium << std::endl;
std::cout << High << std::endl;
return 0;
}Testing an enum value
The variable level holds Medium. The if test matches Medium, so its label line prints.
#include <iostream>
enum Level { Low, Medium, High };
int main() {
Level level = Medium;
if (level == Medium) {
std::cout << "Medium level" << std::endl;
}
return 0;
}Values set by hand
Each name gets its number by hand here. The three values print as 1, 5, and 10.
#include <iostream>
enum Level { Low = 1, Medium = 5, High = 10 };
int main() {
std::cout << Low << std::endl;
std::cout << Medium << std::endl;
std::cout << High << std::endl;
return 0;
}Example
#include <iostream>
enum Size { Small, Medium, Large };
void showSize(Size size) {
switch (size) {
case Small:
std::cout << "Small" << std::endl;
break;
case Medium:
std::cout << "Medium" << std::endl;
break;
case Large:
std::cout << "Large" << std::endl;
break;
}
}
int main() {
showSize(Small);
showSize(Medium);
showSize(Large);
return 0;
}Key points
- The enum keyword starts an enum definition.
- The first name in an enum holds 0 by default.
- Each next name holds a number one higher than the name before it.
- An enum value prints as its number.
- An enum variable holds one value from the set.
- A program can set a number for a name by hand.
In this example, the showSize function holds a switch on a Size value. Each case prints the label for its value. The three calls print Small, Medium, and Large in order.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What number does the first name in a plain enum hold by default?