C++ Enums

C++ Enums

An enum (short for enumeration) is a special type that represents a group of constants (unchangeable values).

Creating an Enum

To create an enum, use the enum keyword, followed by the name of the enum, and separate the enum items with a comma:

Example

enum Level {
  LOW,
  MEDIUM,
  HIGH
};
By default, the first item (`LOW`) has the value `0`, the second (`MEDIUM`) has the value `1`, and so on.

Using an Enum

You can access enum items by creating a variable of the enum type:

Example

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.).


Exercise

?

What is the default integer value of the first item in a C++ enum?