Loading

C++: Enumerations

Enumerations

In this C++ tutorial, we encounter our first programmer-defined type. Unlike the previous data types that we have seen, enumerated types (enums) are not built into the C++ language. Instead, we define an enum as a series of values.

For instance, we can define the months of the year in an enum. The months correspond to integer values, which we can define any way that we wish. However, when creating enumerated types we will generally not be concerned with the actual values. Instead, the enumerated value names will be used to compare to each other to check for equality. In this way, it is only important the integer values be distinct.

The enum above defines the month names to correspond to the values 0 through 11. This might be sufficient if we only want to make checks to see whether one monthly value is equal to another. In this particular case, we would probably want the values to run from 1 to 12 to make conversions to numeric date values. We can define that enum like this:

We could also create an enum for the day of the week and create an instance of the day of the week for today. We might make a check later on to see whether the day is in the range Monday through Friday. If so, we could have our program remind us that we need to go to work or something else like that.

I will just make a few other minor points about enumerations. We can assign two enum values to the same numeric value. For example, we could define keMonday and keTuesday to both have the value zero. This generally is not useful, but it could come in handy on rare occasions.