top of page

C++ Enumeration

In C++, an enumeration (enum) is a user-defined data type that allows you to define a set of named constant values. It provides a way to create symbolic names for integer values, making the code more readable and maintainable. Enumerations are often used to represent a set of related constants or to improve code readability by giving meaningful names to integral values.

Here's the basic syntax for declaring an enumeration in C++:

enum EnumName {
    Constant1,
    Constant2,
    Constant3,
    // ... more constants ...
};

Here's an example of how you can define and use an enumeration in C++:

#include <iostream>// Define an enumeration named 'Color' with three constantsenum Color {
    RED,    // 0
    GREEN,  // 1
    BLUE    // 2
};

int main() {
    // Declare a variable of the 'Color' enumeration type
    Color chosenColor = RED;

    // Use the variable and the constantsif (chosenColor == RED) {
        std::cout << "You chose RED." << std::endl;
    } else if (chosenColor == GREEN) {
        std::cout << "You chose GREEN." << std::endl;
    } else if (chosenColor == BLUE) {
        std::cout << "You chose BLUE." << std::endl;
    }

    // Enumerations are implicitly convertible to integersint colorIntValue = chosenColor;
    std::cout << "The integer value of the chosen color is: " << colorIntValue << std::endl;

    return 0;
}

In this example, we define an enumeration named Color with three constants: RED, GREEN, and BLUE. By default, the first constant is assigned the value 0, and subsequent constants are assigned consecutive integer values, incrementing by 1.

Enumerations in C++ can also have explicitly assigned values, like this:

enum AnotherEnum {
    VALUE1 = 10,
    VALUE2 = 20,
    VALUE3 = 30
};

In this case, VALUE1 will have the value 10, VALUE2 will have the value 20, and so on.

Enumerations are helpful when you need to work with a limited set of related constants, as they can make your code more expressive and easier to understand.

Related Posts

See All

Comments


bottom of page