C++ Enumerated data type

In C++, an enumerated data type, or enum, is a user-defined type that consists of a set of named integral constants. It is used to assign names to integral values, making a program easier to read and maintain. Here’s a basic overview of how to define and use an enum in C++.

Defining an Enum

You define an enum using the enum keyword followed by the name of the enum and a list of named constants enclosed in curly braces {}.

Example:

enum Day {
    Sunday,    // 0
    Monday,    // 1
    Tuesday,   // 2
    Wednesday, // 3
    Thursday,  // 4
    Friday,    // 5
    Saturday   // 6
};

In this example, Day is an enumerated type, and Sunday through Saturday are the enumerators. By default, the enumerators are assigned integer values starting from 0.

Using an Enum

Once you have defined an enum, you can create variables of that enum type and assign them one of the enumerator values.

Example:

Day today = Wednesday;

if (today == Wednesday) {
    std::cout << "It's the middle of the week!" << std::endl;
}

Assigning Specific Values

You can also explicitly assign values to the enumerators:

enum Month {
    January = 1,
    February = 2,
    March = 3,
    April = 4,
    May = 5,
    June = 6,
    July = 7,
    August = 8,
    September = 9,
    October = 10,
    November = 11,
    December = 12
};

Here, January is explicitly assigned the value 1, and the other months are assigned values sequentially.

Enum with a Scoped Enum (C++11 and Later)

C++11 introduced scoped enums, also known as enum class. Scoped enums are more strongly typed and prevent implicit conversions to integer types.

Example:

enum class Color {
    Red,
    Green,
    Blue
};

Color myColor = Color::Red;

if (myColor == Color::Red) {
    std::cout << "The color is Red" << std::endl;
}

Scoped enums do not implicitly convert to integers, which makes them safer to use.

Enum Use Cases

Enums are useful in situations where you have a set of related constants that represent different states or categories, such as days of the week, months of the year, directions (North, South, East, West), and so on.

They make your code more readable and maintainable by allowing you to use descriptive names instead of raw numbers.

Leave a Comment