Scroll Progress Bar

Enumeration

Enumeration (enum) is a user-defined data type in C++ that consists of named integral constants. Enums are used to create a set of meaningful, named values for a variable, making the code more readable and maintainable. Each named constant within an enum is associated with an integer value that starts at 0 by default and increments for each subsequent constant unless specified otherwise. Here's how define and use enums in C++:

Defining an Enum:

define an enum using the enum keyword, followed by the name of the enum type and a list of named constants enclosed in curly braces { }. For example:

Program:

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

In this example, we've defined an enum type named Day with seven constants. By default, Sunday has the value 0, Monday has the value 1, and so on. it can also specify custom integer values for enum constants:

Program:

enum Month {
    January = 1,
    February = 2,
    March = 3,
    // ...
};
Using Enums:

Once you've defined an enum, it can declare variables of that enum type and assign one of its named constants to the variable:

Program:

Day today = Monday;

it can compare enum variables and constants, just like would with integers:

Program:

if (today == Sunday) {
    std::cout << "It's a lazy day!" << std::endl;
}
Switch Statements with Enums:

Enums are often used in switch statements to improve code readability:

Program:

switch (today) {
    case Sunday:
        std::cout << "It's a lazy day!" << std::endl;
        break;
    case Monday:
        std::cout << "Time to work!" << std::endl;
        break;
    // ...
    default:
        std::cout << "Unknown day." << std::endl;
        break;
}
Enum Classes (Scoped Enums):

In C++11 and later versions, it can use enum classes (scoped enums) to create enumerations with scoped, strongly typed constants. This helps avoid naming conflicts and provides better type safety:

Program:

enum class Color {
    Red,
    Green,
    Blue
};

Color chosenColor = Color::Green; // Scoped enum usage

In contrast to regular enums, enum class constants are not implicitly convertible to integers or other enum types, which it can help prevent unintended conversions and errors.

Enums are valuable for making code more expressive and self-documenting by giving meaningful names to integral constants, rather than using "magic numbers" throughout code.


question


answer

question2


answer2