C Enums
A C enum (enumeration) is a type made of named integer constants. Enums replace unclear numbers like 0, 1 and 2 with meaningful names like LOW, MEDIUM and HIGH.
Creating an Enum
By default the first name is 0 and each next name is one more.
#include <stdio.h>
enum Level { LOW, MEDIUM, HIGH };
int main(void) {
enum Level current = MEDIUM;
printf("MEDIUM = %d\n", current);
printf("HIGH = %d\n", HIGH);
return 0;
}MEDIUM = 1 HIGH = 2
Custom Enum Values
You can assign specific values. Names after an assigned one keep counting up from it.
#include <stdio.h>
typedef enum {
HTTP_OK = 200,
HTTP_CREATED, // 201
HTTP_NOT_FOUND = 404
} HttpStatus;
int main(void) {
printf("%d %d %d\n", HTTP_OK, HTTP_CREATED, HTTP_NOT_FOUND);
return 0;
}200 201 404
Enums with switch
Enums and switch work great together; compilers can even warn you when you forget a case.
#include <stdio.h>
typedef enum { RED, YELLOW, GREEN } Light;
const char *action(Light l) {
switch (l) {
case RED: return "Stop";
case YELLOW: return "Slow down";
case GREEN: return "Go";
}
return "Unknown";
}
int main(void) {
printf("%s\n", action(GREEN));
return 0;
}Go
Why Use Enums
- Code reads like plain English.
- Related constants are grouped together.
- Debuggers show enum names instead of raw numbers.
- Compiler warnings help catch missing switch cases.
Frequently asked questions
What is the default value of an enum in C?
The first enumerator is 0 and each following one increases by 1 unless you assign values explicitly.
Should I use enum or #define in C?
Prefer enum for groups of related integer constants. Enums are visible in debuggers, scoped to a type name, and work well with switch warnings.
Can two enum constants have the same value?
Yes, C allows it, for example enum { START = 1, FIRST = 1 }. However, each name must be unique within its scope.