When you have a variable that should only hold one value from a small set — like days of the week or error codes — you could use integers. But enum gives names to those values, making your code self-documenting and less error-prone.
Defining and Using Enums
An enum creates a new type with named constants. By default, the first constant is 0, the next is 1, and so on — but you can set your own values.
#include
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN };
int main() {
enum Day today = WED;
printf("Today is day number %d\n", today);
if (today == SAT || today == SUN) {
printf("Weekend!\n");
} else {
printf("Weekday\n");
}
return 0;
}
Try it Yourself →
Custom Enum Values
You can assign specific integers to enum constants. This is great for representing status codes or bit flags where the numeric value matters.
#include
enum HttpStatus {
OK = 200,
NOT_FOUND = 404,
SERVER_ERROR = 500
};
int main() {
enum HttpStatus status = NOT_FOUND;
printf("Status code: %d\n", status);
if (status == NOT_FOUND) {
printf("Page not found!\n");
}
return 0;
}
Try it Yourself →
When to Use Enums
Use enums whenever a variable should only take one of a fixed set of related values. They make your code safer (you can't accidentally type a wrong number) and more readable (the name tells you what it means).
#include
enum Color { RED, GREEN, BLUE };
void printColor(enum Color c) {
switch (c) {
case RED: printf("Red\n"); break;
case GREEN: printf("Green\n"); break;
case BLUE: printf("Blue\n"); break;
}
}
int main() {
enum Color c = GREEN;
printColor(c);
return 0;
}
Try it Yourself →