C++ Enumeration


Introduction

In C++, an enumeration (or enum) is a user-defined data type that consists of a set of named integer constants. Enumerations are used to make programs more readable by replacing numeric constants with meaningful names.

By using enum, you can define a variable that can take one of the values from a predefined set of constants. Enumerations are useful when you have a set of related values (such as days of the week, months of the year, or statuses in a process) and want to improve code readability and maintainability.

In this guide, we will learn how to define and use enumerations in C++.


1. What is an Enumeration in C++?

An enum in C++ is a data type that allows you to define a set of named integer constants. The syntax of an enum is straightforward:

Syntax for Defining an Enumeration:

enum EnumName {
    CONSTANT1,
    CONSTANT2,
    CONSTANT3,
    // ...
};
  • EnumName: The name of the enumeration.
  • CONSTANT1, CONSTANT2, CONSTANT3: The named constants within the enumeration.

By default, the constants in an enum are assigned integer values starting from 0 unless explicitly specified.


2. Basic Example: Defining and Using an Enumeration

Here’s a basic example of how to define and use an enum in C++:

#include <iostream>
using namespace std;

// Define an enumeration for days of the week
enum Day {
    Sunday,    // 0
    Monday,    // 1
    Tuesday,   // 2
    Wednesday, // 3
    Thursday,  // 4
    Friday,    // 5
    Saturday   // 6
};

int main() {
    // Declare a variable of type Day
    Day today = Wednesday;

    // Output the integer value corresponding to Wednesday
    cout << "Integer value of Wednesday: " << today << endl;

    return 0;
}

Output:

Integer value of Wednesday: 3

Explanation:

  • We defined an enum called Day with days of the week as constants.
  • The constants automatically start with the value 0 (for Sunday), and the subsequent days are assigned increasing integer values (1 for Monday, 2 for Tuesday, etc.).
  • We declared a variable today of type Day and assigned it the value Wednesday.
  • The today variable holds the integer value 3, as Wednesday is the third constant in the enumeration.

3. Specifying Custom Values in an Enumeration

You can also assign custom integer values to the constants in an enumeration. This allows more control over the values used.

Example: Custom Values in Enumeration

#include <iostream>
using namespace std;

// Define an enumeration with custom values
enum Day {
    Sunday = 1,    // Custom value 1
    Monday = 2,    // Custom value 2
    Tuesday = 3,   // Custom value 3
    Wednesday = 4, // Custom value 4
    Thursday = 5,  // Custom value 5
    Friday = 6,    // Custom value 6
    Saturday = 7   // Custom value 7
};

int main() {
    // Declare a variable of type Day
    Day today = Friday;

    // Output the integer value corresponding to Friday
    cout << "Integer value of Friday: " << today << endl;

    return 0;
}

Output:

Integer value of Friday: 6

Explanation:

  • We explicitly specified custom values for each day of the week.
  • In this case, Sunday starts at 1, and the values increment accordingly. Friday will have the value 6.

4. Enum with Non-Sequential Values

Sometimes, you may want to have non-sequential values for your enumeration constants. This is also possible by manually assigning specific values to each constant.

Example: Non-sequential Values in Enumeration

#include <iostream>
using namespace std;

// Define an enumeration with non-sequential values
enum Day {
    Sunday = 1,    // Custom value 1
    Monday = 10,   // Custom value 10
    Tuesday = 20,  // Custom value 20
    Wednesday = 30, // Custom value 30
    Thursday = 40,  // Custom value 40
    Friday = 50,    // Custom value 50
    Saturday = 60   // Custom value 60
};

int main() {
    // Declare a variable of type Day
    Day today = Tuesday;

    // Output the integer value corresponding to Tuesday
    cout << "Integer value of Tuesday: " << today << endl;

    return 0;
}

Output:

Integer value of Tuesday: 20

Explanation:

  • We assigned specific, non-sequential values to the constants in the Day enumeration.
  • Tuesday now holds the value 20 instead of 2 or another default value.

5. Enum as a Type

You can use an enumeration type to declare variables, as shown in the previous examples. Enums provide better readability and organization compared to using plain integer constants.

Example: Enum as a Type

#include <iostream>
using namespace std;

// Define an enumeration for status codes
enum StatusCode {
    OK = 200,       // Successful request
    NotFound = 404, // Resource not found
    Forbidden = 403, // Forbidden access
    InternalError = 500 // Server error
};

int main() {
    // Declare a variable of type StatusCode
    StatusCode status = NotFound;

    // Check the status code
    if (status == NotFound) {
        cout << "Error: Resource not found" << endl;
    }

    return 0;
}

Output:

Error: Resource not found

Explanation:

  • We defined an enum called StatusCode to represent HTTP status codes.
  • By using enums, the code is more readable and easier to maintain, as we don't need to rely on magic numbers like 404.

6. Using Enum with Switch Statements

Enums work well with switch statements, which makes it easier to handle different cases based on the enum value.

Example: Using Enum with Switch Statement

#include <iostream>
using namespace std;

// Define an enumeration for seasons
enum Season {
    Spring = 1,
    Summer,
    Autumn,
    Winter
};

int main() {
    // Declare a variable of type Season
    Season currentSeason = Winter;

    // Use switch-case to handle different seasons
    switch (currentSeason) {
        case Spring:
            cout << "It's Spring!" << endl;
            break;
        case Summer:
            cout << "It's Summer!" << endl;
            break;
        case Autumn:
            cout << "It's Autumn!" << endl;
            break;
        case Winter:
            cout << "It's Winter!" << endl;
            break;
        default:
            cout << "Invalid season!" << endl;
    }

    return 0;
}

Output:

It's Winter!

Explanation:

  • We use the Season enum to declare the current season and use a switch statement to print a message based on the season.