C - Enum

 enumeration (enum) is a user-defined data type that allows you to define a set of named constants. It provides a way to associate meaningful names with a set of related values, making the code more readable and maintainable. Here's an explanation of enumerations in C:

Enum Declaration:

To define an enumeration, you use the enum keyword followed by the name of the enumeration and a list of named constants enclosed in curly braces.

enum enumName {
    constant1,
    constant2,
    constant3,
    // ...
};

enumName: The name given to the enumeration.

constant1, constant2, constant3, etc.: The named constants or enumerators associated with the enumeration.

#include <stdio.h>
// Enumeration declaration
enum Day {
    MON,
    TUE,
    WED,
    THU,
    FRI,
    SAT,
    SUN
};
int main() {
    // Enumeration variable declaration
    enum Day today;
    // Assigning a value to the enumeration variable
    today = FRI;
    // Switch statement using enumeration
    switch (today) {
        case MON:
            printf("Today is Monday.\n");
            break;
        case TUE:
            printf("Today is Tuesday.\n");
            break;
        case WED:
            printf("Today is Wednesday.\n");
            break;
        case THU:
            printf("Today is Thursday.\n");
            break;
        case FRI:
            printf("Today is Friday.\n");
            break;
        case SAT:
            printf("Today is Saturday.\n");
            break;
        case SUN:
            printf("Today is Sunday.\n");
            break;
        default:
            printf("Invalid day.\n");
    }
    return 0;
}

In this example, an enumeration named Day is defined with seven named constants representing the days of the week. Inside main(), an enumeration variable today is declared and assigned the value FRI. A switch statement is used to print a message based on the value of today.

Enumerations are particularly useful when you want to represent a set of related values that have a logical order or relationship. They improve code readability by using descriptive names instead of arbitrary values.

You can also assign specific values to the enumerators, which can be useful in certain cases:

enum Month {
    JAN = 1,
    FEB,
    MAR,
    // ...
};

In this example, JAN is explicitly assigned a value of 1, and subsequent enumerators FEB, MAR, etc., are assigned values sequentially.