Understanding Enumerators in C

Enumeration (or enum) is a user-defined data type in C language. It is used to assign meaningful names to integral constants, making a program easier to read and maintain.
Syntax
The keyword enum is used to declare an enumeration.
enum enum_name {const1, const2, ....... constn};By default, const1 is 0, const2 is 1, and so on. However, you can change these default values during declaration.
Example:
enum fruits {apple, mango, orange, grapes};Example 1: Basic Working
A simple program to demonstrate how to declare and use an enum variable.
#include <stdio.h>
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
void main() {
enum week today;
today = Wednesday;
printf("The value of today is %d", today + 1);
}Output: The value of today is 4 (since Wednesday is at index 3).
Example 2: Enum in Switch Statement
Enums pair perfectly with switch statements, making your control flow logic much clearer than using arbitrary numbers.
#include <stdio.h>
enum days {sunday=1, monday, tuesday, wednesday, thursday, friday, saturday};
void main() {
enum days d;
d = monday;
switch(d) {
case sunday:
printf("Today is sunday");
break;
case monday:
printf("Today is monday");
break;
case tuesday:
printf("Today is tuesday");
break;
case wednesday:
printf("Today is wednesday");
break;
case thursday:
printf("Today is thursday");
break;
case friday:
printf("Today is friday");
break;
case saturday:
printf("Today is saturday");
break;
}
}Example 3: Enum with Loop
Since enum constants are internally integers, we can iterate through them.
#include <stdio.h>
enum year {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
int main() {
int i;
for (i = Jan; i <= Dec; i++)
printf("%d ", i);
return 0;
}C23: Typed Enums are Here!
The C23 standard (ISO/IEC 9899:2024), finalized in 2024, introduced typed enumerations — a long-requested feature that lets you specify the underlying integer type of an enum:
// C23: Specify enum underlying type
enum Status : unsigned char { IDLE, RUNNING, ERROR };
// The size is now guaranteed to be 1 byte
printf("%zu
", sizeof(enum Status)); // Output: 1Before C23, the size of an enum was implementation-defined (usually int). This new feature brings C closer to C++ in terms of type safety and is critical for embedded systems programming where memory layout matters.
Why Use Enums? (Extra Insights)
1. Readability
if (day == Sunday) is much easier to understand than if (day == 0). It tells the programmer what the value represents.
2. Maintainability
If you need to change the values, you only change them in the enum definition, not every place the number 0 or 1 was used in the code.
3. Enums vs. Macros (#define)
Enums follow scope rules, whereas macros are global. Enums also automatically assign values, whereas macros require manual assignment for every constant.