C Enumerations (enum): Custom Values, Type Safety & Switch State Machines
Welcome to Phase 12 (Chapter 31): C Enumerations (enum) โ Custom Values, Type Safety & Switch State Machines Masterclass! Writing raw numbers like 0, 1, 2, 3 in code to represent states (e.g. PENDING, PROCESSING, COMPLETED, FAILED) leads to cryptic, unreadable, and error-prone code ("Magic Numbers"). In C, Enumerations (enum) allow creating human-readable named integer constants that improve code clarity and type safety. In this exhaustive textbook-grade guide, you will master enum declarations, auto-increment rules, custom explicit integer values (like HTTP status codes 200, 404, 500), enum state machine dispatchers using switch-case, and industry-standard naming conventions.
An Enumeration is a user-defined type consisting of a set of named integer constants. By default, the C compiler assigns integer values starting from 0 and auto-increments each subsequent symbol by 1:
๐ Auto-Increment Default Rule:
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN };
โข MON = 0, TUE = 1, WED = 2, ..., SUN = 6.
You can assign custom integer values to enum constants (e.g. HTTP status codes or hardware error flags):
#include <stdio.h>
// Custom Enum Explicit Values
typedef enum {
HTTP_OK = 200,
HTTP_CREATED = 201,
HTTP_BAD_REQUEST = 400,
HTTP_NOT_FOUND = 404,
HTTP_SERVER_ERROR = 500
} HttpStatus;
void handleResponse(HttpStatus status) {
switch (status) {
case HTTP_OK:
printf("[200 OK] Request succeeded!\n");
break;
case HTTP_CREATED:
printf("[201 CREATED] Resource created successfully!\n");
break;
case HTTP_BAD_REQUEST:
printf("[400 BAD REQUEST] Invalid client payload!\n");
break;
case HTTP_NOT_FOUND:
printf("[404 NOT FOUND] Requested URL does not exist!\n");
break;
case HTTP_SERVER_ERROR:
printf("[500 INTERNAL ERROR] Server crashed!\n");
break;
default:
printf("Unknown status code (%d)\n", status);
break;
}
}
int main(void) {
HttpStatus code1 = HTTP_OK;
HttpStatus code2 = HTTP_NOT_FOUND;
handleResponse(code1);
handleResponse(code2);
return 0;
}
Q1: What is the underlying memory size of an enum variable in C?
In standard C, enum variables are stored as signed int (typically 4 bytes). Some compilers (GCC/Clang with -fshort-enums) optimize enum size to 1 or 2 bytes if all enum values fit in smaller integer ranges.
Q2: Can two enum constants share the exact same integer value?
Yes! Writing enum Status { FALSE = 0, NO = 0, TRUE = 1, YES = 1 }; is 100% valid in C. Both FALSE and NO map to integer 0.
Run this traffic light state machine in our live GCC compiler:
#include <stdio.h>
typedef enum { RED, YELLOW, GREEN } TrafficLight;
int main(void) {
TrafficLight light = RED;
if (light == RED) {
printf("STOP! Light is RED (%d)\n", light);
}
return 0;
}