Enumerations in C

In C programming language, an enumeration (or enum for short) is a user-defined data type that consists of a set of named integer constants. Enumerations enable the programmer to create a set of named values that can be used in a program.

To declare an enumeration in C, you need to define its named constants. Here’s an example of how to declare an enumeration in C:

enum Color {
    RED,
    GREEN,
    BLUE
};

In this example, we declare an enumeration named “Color” that has three named constants: RED, GREEN, and BLUE. By default, the values of the constants start at 0 and increment by 1 for each subsequent constant.

We can create variables of the enumeration type by using the “enum” keyword followed by the enumeration name. Here’s an example of how to create a variable of the “Color” enumeration type:

enum Color c1;

In this example, we create a variable named “c1” of the “Color” enumeration type.

We can assign values to enumeration variables using their named constants. Here’s an example of how to assign values to a “Color” enumeration variable:

enum Color c1 = RED;
enum Color c2 = BLUE;

In this example, we create two “Color” enumeration variables named “c1” and “c2” and assign them the values RED and BLUE, respectively.

We can also use switch statements with enumeration variables to make decisions based on their values. Here’s an example of how to use a switch statement with a “Color” enumeration variable:

enum Color c1 = GREEN;

switch (c1) {
    case RED:
        printf("The color is red\n");
        break;
    case GREEN:
        printf("The color is green\n");
        break;
    case BLUE:
        printf("The color is blue\n");
        break;
    default:
        printf("Invalid color\n");
        break;
}

In this example, we create a “Color” enumeration variable named “c1” and assign it the value GREEN. We then use a switch statement to print a message to the console based on the value of “c1”.

Enumerations in C are a powerful feature that enable the programmer to create named integer constants that can be used in a program. However, it is important to use enumerations carefully to avoid type compatibility issues and naming conflicts.