Last Updated on March 28, 2022 by Ria Pathak
Enumerated type (or enumeration) in C++ is a user defined data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The C++ enum constants are static and final implicitly. Enumerations are declared via the enum keyword.
Each enumerator is automatically assigned an integer value based on its position in the enumeration list. By default, the first enumerator is assigned the integer value 0, and each subsequent enumerator has a value one greater than the previous enumerator.
Example:
// Declare a new enumeration named Week
enum Week {
// Here are the enumerators
// These define all the possible values this type Week can hold
Monday, //assigned 0
Tuesday, //assigned 1
Wednesday, //assigned 2
Thursday, //assigned 3
Friday, //assigned 4
Saturday, //assigned 5
Sunday //assigned 6
};
int main() {
Week day;
day = Friday;
cout << "Day: " << day + 1 << endl;
return 0;
}
Output:
Day: 5
It is possible to explicitly define the value of enumerator. These integer values can be positive or negative and can share the same value as other enumerators. Any non-defined enumerators are given a value one greater than the previous enumerator.
Example:
enum Animal {
ANIMAL_CAT = -3,
ANIMAL_DOG,
// assigned -2 ANIMAL_PIG,
// assigned -1 ANIMAL_HORSE = 5,
ANIMAL_CHICKEN
// assigned 6 };
The compiler will not implicitly convert an integer to an enumerated value.
The following will produce a compiler error:Animal animal = 5; [will cause compiler error]
Each enumerated type is considered a distinct type. Consequently, trying to assign enumerators from one enum type to another enum type will cause a compile error.Animal animal = Monday; [It will cause compilation error as we try to assign Week enum type to Animal enum type]
Key Points:
- enum improves type safety
- enum can be easily used in switch
- enum can be traversed
- enum can have fields, constructors and methods
This article tried to discuss Enumeration in C++. Hope this blog helps you the concept and implementation. To practice more and build your foundation you can check out Prepbytes Courses.