Let's name our integer values: Enums

In C programming, enums (enumerations) are user-defined data types that consist of named integral constants. Enums are used to make the code more readable and maintainable by assigning meaningful names to a set of related constants.

Here's an example of how enums work in C, including different cases of initialization:

#include <stdio.h>

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

int main() {
    // Case 1: Simple enum variable declaration
    enum Days today;
    today = Wednesday;

    printf("Today is day number: %d\n", today);  // Output: Today is day number: 3

    // Case 2: Declaration and initialization in a single line
    enum Days yesterday = Tuesday;
    printf("Yesterday was day number: %d\n", yesterday);  // Output: Yesterday was day number: 2

    // Case 3: Non-sequential values
    enum Months {
        January = 1,
        February,
        March,
        April,
        May,
        June,
        July,
        August,
        September,
        October,
        November,
        December
    };

    enum Months currentMonth = September;
    printf("We are in the month of September, which is month number: %d\n", currentMonth);  // Output: We are in the month of September, which is month number: 9

    // Case 4: Using typedef to create an alias for the enum type
    typedef enum {
        Red,
        Green,
        Blue
    } Color;

    Color selectedColor = Green;
    printf("Selected color is: %d\n", selectedColor);  // Output: Selected color is: 1

    return 0;
}

In this example:

  • Case 1 demonstrates the declaration and assignment of an enum variable.

  • Case 2 shows how to declare and initialize an enum variable in a single line.

  • Case 3 illustrates non-sequential values for the enum constants.

  • Case 4 introduces the use of typedef to create an alias for the enum type.

Enums in C provide a convenient way to represent sets of related constants, making the code more readable and reducing the likelihood of errors related to using magic numbers.