An enum (short for enumeration) is a special type that represents a group of constants (unchangeable values).
To create an enum, use the enum keyword, followed by the name of the enum, and separate the enum items with a comma:
enum Level {
LOW,
MEDIUM,
HIGH
};
You can access enum items by creating a variable of the enum type:
int main() {
// Create an enum variable and assign a value to it
Level myVar = MEDIUM;
// You can use enums in switch statements
switch (myVar) {
case LOW:
cout << "Low Level";
break;
case MEDIUM:
cout << "Medium Level";
break;
case HIGH:
cout << "High Level";
break;
}
return 0;
}
Enums are great for readability, especially when variables can only have a specific set of distinct values (like days of the week, states in a game, etc.).
What is the default integer value of the first item in a C++ enum?