Enumerations (enum)

Lesson 6.5: Enumerations (enum)


In this lesson, you'll discover enumerations (enum), a powerful tool in C that allows you to create your own named integer constants. This improves code readability, maintainability, and type safety.


What are Enumerations?


Named Constants: Enumerations define a set of named integer constants. These constants represent a group of related values, making your code more self-documenting and easier to understand.

Improved Readability: Instead of using magic numbers (e.g., 0 for Monday, 1 for Tuesday), you can use descriptive names like Monday and Tuesday, making your code more intuitive.

Type Safety: Enumerations create a new type, preventing you from accidentally assigning invalid values to your variables.

Underlying Integer Values: By default, the first constant in an enum is assigned the value 0, and each subsequent constant is assigned the next integer value. You can also explicitly assign integer values to enum constants.

Syntax


C

enum enumName {

    constant1,

    constant2,

    // ... more constants

};

Example: Days of the Week


C

enum Day {

    Monday,  // 0

    Tuesday, // 1

    Wednesday,

    Thursday,

    Friday,

    Saturday,

    Sunday    // 6

};


int main() {

    enum Day today = Wednesday;


    if (today == Sunday || today == Saturday) {

        printf("It's the weekend!\n");

    } else {

        printf("It's a weekday.\n");

    }


    return 0;

}

Assigning Explicit Values


C

enum Direction {

    North = 10,

    East = 20,

    South = 30,

    West = 40

};

Working with Enums in Switch Statements


Enumerations are particularly useful in switch statements:


C

switch (today) {

    case Monday:

        printf("Start of the work week!\n");

        break;

    case Friday:

        printf("Almost the weekend!\n");

        break;

    default:

        printf("Just another day...\n");

}

Key Points:


Improved Readability: Use meaningful names for enum constants to make your code self-explanatory.

Type Safety: Enums create a distinct type, helping you catch errors at compile time.

Customization: You can explicitly assign integer values to enum constants.

Switch Statements: Enums work well with switch statements to handle different cases based on enum values.

Hands-On Exercise:


Create an enum for the months of the year.

Write a program that prompts the user to enter a month number.

Use a switch statement to print the corresponding month name based on the user's input.

Course Syllabus