C programming - Enumeration
In C programming, an enum (short for "enumeration") is a user-defined data type that consists of a set of named constants. enum values are typically used to represent a set of related constants that have a fixed value and are not likely to change.
To define an enum in C, you use the enum keyword followed by a set of constant names enclosed in braces. For example, the following code defines an enum named Month that contains the names of the twelve months:
enum Month {
JANUARY,
FEBRUARY,
MARCH,
APRIL,
MAY,
JUNE,
JULY,
AUGUST,
SEPTEMBER,
OCTOBER,
NOVEMBER,
DECEMBER
};
Each constant in the enum is assigned a value that starts at 0 for the first constant and increments by 1 for each subsequent constant. You can also explicitly assign values to enum constants, like this:
enum Day {
MONDAY = 1,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
};
In this example, the MONDAY constant is assigned the value 1, and the subsequent constants are assigned values that increment by 1.
To declare a variable of an enum type, you simply use the enum name followed by the variable name. For example, the following code declares a variable named currentMonth of type Month and initializes it to MARCH:
enum Month {
JANUARY,
FEBRUARY,
MARCH,
APRIL,
MAY,
JUNE,
JULY,
AUGUST,
SEPTEMBER,
OCTOBER,
NOVEMBER,
DECEMBER
};
enum Month currentMonth = MARCH;
enum values can be compared using the == and != operators, but you cannot perform arithmetic operations on enum values.
enum values are typically used in switch statements and to improve code readability by using descriptive names instead of hard-coded numeric constants.
