Enumerations (Enum) in C
An enum (Enumeration) in C is a user-defined data type where values are assigned symbolic names.
Enums make code more readable, meaningful, and easier to maintain instead of using raw numbers.
What is an Enum?
An enumeration is a list of named integer constants. By default, the first value starts from 0, and the rest increase by 1.
- Improves readability
- Avoids magic numbers
- Used in menus, days, months, modes
- Helps create meaningful constants
Syntax of Enum
enum enum_name {
value1,
value2,
value3
};
How Enum Works?
- The first value is 0 unless specified
- Each next value increases by 1
- You can assign custom values
- Multiple values can have the same number
Advantages of Enum
- Makes code structured and readable
- Suitable for categories and fixed sets
- Can be used in switch-case
- Better than using integers directly
Examples (5 Examples)
Example 1 – Basic Enum
#include <stdio.h>
enum Days { MON, TUE, WED, THU, FRI, SAT, SUN };
int main() {
enum Days today = WED;
printf("%d", today);
return 0;
}
Example 2 – Enum with Custom Values
#include <stdio.h>
enum Level { LOW = 1, MEDIUM = 5, HIGH = 10 };
int main() {
enum Level l = HIGH;
printf("%d", l);
return 0;
}
Example 3 – Enum in Switch Case
#include <stdio.h>
enum Menu { ADD = 1, EDIT, DELETE };
int main() {
enum Menu choice = EDIT;
switch(choice){
case ADD: printf("Add selected"); break;
case EDIT: printf("Edit selected"); break;
case DELETE: printf("Delete selected"); break;
}
return 0;
}
Example 4 – Enum for Boolean
#include <stdio.h>
enum Bool { FALSE, TRUE };
int main() {
enum Bool status = TRUE;
if(status)
printf("Success");
else
printf("Failure");
return 0;
}
Example 5 – Enum for Months
#include <stdio.h>
enum Month { JAN=1, FEB, MAR, APR, MAY };
int main() {
enum Month m = APR;
printf("Month number: %d", m);
return 0;
}
Practice Questions
- What is an enum? Why is it used?
- Create an enum for traffic light colors.
- What is the default value of the first enum item?
- Can we assign custom integer values? Give example.
- Write an enum to represent weather conditions.
Practice Task:
Create an enum for vehicle types (Car, Bus, Truck, Bike)
and print a message based on user choice.