Enumerations (enum) and typedef
Avoid confusing magic numbers in your code by assigning meaningful human-readable names to constant states.
What is it?
An enumeration (`enum`) is a user-defined data type consisting of a set of named integer constants.
Why is it used?
Improves code readability and self-documentation for states like days of the week, order statuses, or user roles.
Detailed Explanation
Enum Mechanics:
• By default, enum values start at 0 and increment by 1 (`STATUS_PENDING = 0`, `STATUS_ACTIVE = 1`, etc.).
• Custom Values: You can assign custom values: `enum Status { NEW = 1, VERIFIED = 5, CLOSED = 10 };`.
• Paired with `typedef`, enums behave like custom named types.
Syntax Structure
Syntax Blueprint
typedef enum {
ROLE_STUDENT,
ROLE_INSTRUCTOR,
ROLE_ADMIN
} UserRole;
Code Example
C Code
#include <stdio.h>
// Defining Course Admission Status Enum
typedef enum {
ENQUIRY_NEW, // 0
ENQUIRY_CONTACTED, // 1
ENQUIRY_ENROLLED, // 2
ENQUIRY_CLOSED // 3
} EnquiryStatus;
const char* get_status_label(EnquiryStatus status) {
switch (status) {
case ENQUIRY_NEW: return "New Enquiry";
case ENQUIRY_CONTACTED: return "Counselor Contacted";
case ENQUIRY_ENROLLED: return "Student Enrolled";
case ENQUIRY_CLOSED: return "Lead Closed";
default: return "Unknown";
}
}
int main() {
EnquiryStatus current_lead = ENQUIRY_ENROLLED;
printf("Enquiry Status Code: %d\n", current_lead);
printf("Enquiry Status Label: %s\n", get_status_label(current_lead));
return 0;
}
Explanation of the Code
• `EnquiryStatus` replaces cryptic integer codes (0, 1, 2) with meaningful names.
• Works with `switch` statements to return human-readable labels.
Expected Output
Enquiry Status Code: 2
Enquiry Status Label: Student Enrolled
Real-World Application
Used across the Linux kernel and HTTP server status code engines.
Common Mistakes to Avoid
• Treating enums as strings (enums in C are purely integer constants under the hood).
• Duplicating enum member names in the same scope.
Quick Practice Challenge
Create an enum `Day` representing days of the week starting from Monday = 1.
Key Takeaways
• Enums assign readable names to integer constants.
• Defaults start at 0 and increment by 1.
• Pair with `typedef` for clean custom type aliases.