Skip to main content

Enumerations

Introduction to Enumerations in C++

Enumerations, commonly known as 'enums', are a type of user-defined data structure that consists of integral constants. They allow you to define a new type and then create variables of that type. Enums are used to make the code more readable and manageable by assigning names to integral constants which make a program easy to read and maintain.

Declaring Enumerations

In C++, enumeration is declared using the keyword enum. Here's a simple example of how to declare an enumeration:

enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

In this example, Day is the name of the enumeration and Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday are the enumerators.

Using Enumerations

After declaring an enumeration, we can use it to declare variables. For example:

Day today;
today = Wednesday;

In this case, today is a variable of type Day.

Values of Enumerators

By default, the value of the first enumerator is 0, the value of the second enumerator is 1, the third is 2, and so on. However, C++ allows you to change the default values of the enumerators. Here's how:

enum Day { Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

In this case, Sunday is 1, Monday is 2, Tuesday is 3, and so on. If you assign a value to any enumerator, then the next enumerator will automatically take the value of the previous enumerator plus one.

Accessing Enumerators

To access the value of an enumerator, simply print it as you would print a normal variable. For example:

cout << today; // If today is Wednesday, it will print: 3

Enumerations with Loops

Enumerations can also be used with loops. For example:

for (Day d = Sunday; d <= Saturday; d = static_cast<Day>(d + 1)) {
cout << d << endl;
}

This will print the values of all days from Sunday to Saturday.

Enumerations and Switch Statements

Enumerations are very useful with switch statements. Here's an example:

switch (today) {
case Sunday:
cout << "Today is Sunday.";
break;
case Monday:
cout << "Today is Monday.";
break;
// And so on for the other days
}

This will print the name of the day stored in the today variable.

Conclusion

Enumerations in C++ are a useful tool for making your code more readable and manageable. They allow you to assign names to integral constants, which makes your program easier to understand and maintain. Whether you're using them with loops, switch statements, or just on their own, enumerations are a valuable part of any C++ programmer's toolbox.