Metadata

  • ๐Ÿ“… Date :: 12-06-2025
  • ๐Ÿท๏ธ Tags :: cpp

Notes

Detailed and Elaborative Notes on Enums in C++

1. What is an Enum?

An enum (short for enumeration) in C++ is a user-defined data type that consists of named integer constants. It allows you to define a set of related values under a single name, which makes your code more readable and maintainable. Enums are particularly useful when you have a fixed set of options and want to work with descriptive names instead of raw numeric values.

In C++, enums are typically used for variables that can only have one of a small set of possible values. For example, days of the week, months, or even options like colors, error codes, and so on. They help improve the clarity of your code by using names instead of numbers.

2. Basic Structure of an Enum

Hereโ€™s the basic syntax of how to define an enum in C++:

enum EnumName {
    Name1 = value1,
    Name2 = value2,
    Name3 = value3,
    // more names and values
};
 
  • EnumName: The identifier for the enum type.
  • Name1, Name2, Name3: These are the enumeratorsโ€”named integer constants within the enum.
  • value1, value2, value3: These are the optional integer values associated with each enumerator.

Example: Letโ€™s consider defining an enum for the days of the week:

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

In this example:

  • Sunday is associated with the value 0,
  • Monday with 1, and so on.

By default, if no value is specified, C++ automatically assigns the values starting from 0 and increments by 1 for each subsequent name. So, if you donโ€™t explicitly assign values, the days would be 0 through 6 automatically.

3. Using Enums in Code

Once an enum is defined, you can declare variables of that enum type and assign one of the values from the enum. Enums provide meaningful names, making the code more readable than using plain integers.

Example of Declaring an Enum Variable:

Day today = Sunday;
 

In this example, today is a variable of type Day, and itโ€™s initialized to the value Sunday.

You can then use this enum variable in a switch statement, which normally requires an integer. Here, because Day is an enum, we can switch on today directly:

switch (today) {
    case Sunday:
        std::cout << "It's Sunday!" << std::endl;
        break;
    case Monday:
        std::cout << "It's Monday!" << std::endl;
        break;
    // other cases...
}
 

In the switch statement, the cases correspond to the names (Sunday, Monday, etc.) of the enum, not their underlying integer values. This makes the code cleaner and more understandable.

4. Enums and Switch Statement

Switch statements typically work with integers, and you cannot directly use strings with switches. However, with enums, you can use descriptive names like Sunday, Monday, etc., in place of integer values in the switch statement.

Example of Switch with Enums:

Day today = Sunday;
 
switch (today) {
    case Sunday:
        std::cout << "Relaxing day!" << std::endl;
        break;
    case Monday:
        std::cout << "Back to work!" << std::endl;
        break;
    // other cases...
    default:
        std::cout << "Invalid day!" << std::endl;
}
 

This switch statement will check the value of today, and depending on whether itโ€™s Sunday, Monday, or another day, it will print the corresponding message.

5. Benefits of Enums:

  • Readability: Enums improve the readability of the code. Instead of dealing with arbitrary numbers like 0, 1, 2, etc., you can use meaningful names, such as Sunday, Monday, etc.
  • Prevents Invalid Values: Since enums restrict the variable to one of the predefined values, you canโ€™t accidentally assign a random integer to an enum variable.
  • Maintainability: Enums are easier to maintain as you only need to modify the enum definition in one place rather than changing every integer that represents a day or an option.

6. Implicit Integer Values

If you donโ€™t explicitly assign values to the enumerators, C++ will automatically assign integers starting from 0 and incrementing by 1.

Example:

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

In this case, Sunday gets the value 0, Monday gets 1, and so on, without needing to manually assign each value.

7. Example: Using Enum with Switch and Integer Values

Letโ€™s use enum in a switch statement while assigning integer values to the days of the week:

enum Day {
    Sunday = 0,
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6
};
 
int main() {
    Day today = Friday;
 
    switch (today) {
        case Sunday:
            std::cout << "It's Sunday!" << std::endl;
            break;
        case Friday:
            std::cout << "It's Friday!" << std::endl;
            break;
        // other cases...
    }
 
    return 0;
}
 

Here, the today is set to Friday (which corresponds to 5), and the program will output: "It's Friday!".

8. Enums with Custom Values

While the default behavior is to assign integer values starting from 0, you can assign custom values to each enumerator. For example, you could assign a specific number to each day of the week based on your own logic.

Example of Custom Values:

enum Day {
    Sunday = 10,
    Monday = 20,
    Tuesday = 30,
    Wednesday = 40,
    Thursday = 50,
    Friday = 60,
    Saturday = 70
};
 

9. Error Handling with Enums

Enums provide a mechanism to ensure that only valid values from the set are assigned to the enum variable. If you try to assign a value that doesnโ€™t exist in the enum set, the compiler will raise an error:

Day today = PizzaDay;  // Error: 'PizzaDay' was not declared
 

This prevents invalid values from being used and helps avoid bugs in the program.

10. Additional Enum Examples:

  • Flavors Enum:

    enum Flavor {
        Vanilla,
        Chocolate,
        Strawberry,
        Mint
    };
     
  • Planets Enum:

    enum Planet {
        Mercury = 1,
        Venus = 2,
        Earth = 3,
        Mars = 4,
        Jupiter = 5,
        Saturn = 6,
        Uranus = 7,
        Neptune = 8,
        Pluto = 9
    };
     
  • Colors Enum:

    enum Color {
        Red,
        Green,
        Blue,
        Yellow
    };
     

11. Conclusion:

Enums are a powerful feature in C++ that allow you to define a set of named integer constants, making your code more readable, maintainable, and error-free. They are particularly useful when you have a fixed set of options (like days of the week, colors, or types of events) and want to represent them with meaningful names instead of raw numbers.

  • Enums can be used with switch statements to replace integer values with descriptive names.
  • You can assign custom values to the enumerators, though the default assignment is 0 and increments by 1.
  • Enums help prevent invalid values by restricting the variable to one of the predefined values in the set.

References