C Enumeration

An enumeration in C is a user-defined data type that consists of a set of named constants. Enumerations are used to represent a group of named values, making the code easier to read and maintain.

The syntax for defining an enumeration in C is as follows:

1enum enumeration_name 2{ 3 constant1, 4 constant2, 5 constant3, 6 ... 7};

Once an enumeration has been defined, you can declare variables of that enumeration type using the enumeration name. For example:

1enum colors 2{ 3 red, 4 green, 5 blue 6}; 7 8enum colors color;

You can access the values of an enumeration using the enumeration constant names. For example:

1color = red;

Example: Enumeration in C

The following example demonstrates the use of enumerations in C:

1#include <stdio.h> 2 3enum colors 4{ 5 red, 6 green, 7 blue 8}; 9 10int main() 11{ 12 enum colors color; 13 color = red; 14 printf("The color is: "); 15 switch(color) 16 { 17 case red: 18 printf("red\n"); 19 break; 20 case green: 21 printf("green\n"); 22 break; 23 case blue: 24 printf("blue\n"); 25 break; 26 } 27 return 0; 28}

The output of this program is:

1The color is: red

In this example, an enumeration named colors is defined with three constants: red, green, and blue. A variable color of type colors is declared and initialized with the value red. The value of color is then used in a switch statement to determine which message to print to the console.