Table of Contents
An enumeration is a user-defined data type that represents a fixed set of named integral constants. Enumerations improve code readability by allowing meaningful names to be used instead of numeric values.
Each enumerator is assigned an integer value. By default, the first enumerator has the value 0, and each subsequent enumerator is assigned the next integer value unless explicitly specified.
Source Code #
#include <iostream>
enum Day
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
};
int main()
{
Day today = Wednesday;
std::cout << "Numeric value: " << today << '\n';
return 0;
}
Output #
Numeric value: 3
Explanation #
- The
enumkeyword defines a user-defined enumeration type namedDay. - Each identifier inside the enumeration is called an enumerator.
- By default, the first enumerator (
Sunday) is assigned the value0. - Each subsequent enumerator is assigned the next consecutive integer value.
Day today = Wednesday;declares a variable of typeDayand initializes it with the enumeratorWednesday.- When an enumeration variable is sent to
std::cout, its underlying integer value is printed. - Enumerations make programs easier to read by replacing numeric constants with descriptive names.
return 0;terminates the program successfully.