Enums in C++

Enums in C++, also known as enumeration is a data type which consist of data where every possible value is defined as a constant. When you are declaring an Enum identifier, they are often named with a capital letter and the values inside are declared with all capital letters. Each Enum is automatically assigned an integer value based on its position in the enumeration list. By default, the first Enum is assigned the integer value of 0, then has a value one greater than the previous Enum.

enum Rainbow
{
 COLOR_RED, // assigned 0
 COLOR_ORANGE, // assigned 1
 COLOR_YELLOW, // assigned 2
 COLOR_GREEN, // assigned 3
 COLOR_BLUE, // assigned 4
 COLOR_INDIGO, // assigned 5
 COLOR_VIOLET, // assigned 6
};
 
Rainbow paint = COLOR_YELLOW;
std::cout << paint;

When defining an Enum, it is possible to specify a value for every constant in the Enum.

enum Rainbow
{
 COLOR_RED = 5, 
 COLOR_ORANGE = 15, 
 COLOR_YELLOW = 30, 
 COLOR_GREEN = 20, 
 COLOR_BLUE = 48, 
 COLOR_INDIGO = 80, 
 COLOR_VIOLET = 220, 
};
 
Rainbow paint = COLOR_YELLOW;
std::cout << paint;

The best time to declare an Enum is when you are defining a set of related identifiers. Some more examples could include an enum of cars, books, cards, items etc.

Share this post