Enumerations in C are user-defined data types that allow the programmer to define a set of named constants with integer values. Each named constant in an enumeration is assigned a unique integer value, which can be used to represent a specific state or value in the program.
To define an enumeration in C, the enum keyword is used, followed by a set of named constants, each separated by a comma. Here is an example of an enumeration for the days of the week:
enum Days {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
};
In this example, the Days enumeration contains seven named constants, each representing a day of the week. By default, the first named constant is assigned the value of 0, the second is assigned the value of 1, and so on.
However, the programmer can assign specific integer values to the named constants in the enumeration. Here is an example:
enum Colors {
RED = 1,
GREEN = 2,
BLUE = 4,
YELLOW = 8
};
In this example, the Colors enumeration contains four named constants, each representing a color. The first named constant, RED, is assigned the value of 1, the second named constant, GREEN, is assigned the value of 2, and so on. The programmer can assign any integer value to the named constants in the enumeration.
Enumerations in C can be useful in situations where a set of named constants needs to be used in the program, and it is easier to remember the names of the constants than their corresponding integer values. Enumerations can also make the program more readable and easier to understand.