Enumeration (enum) in C
What does if (day == 3) mean? Wednesday? Thursday? Nobody knows without a comment. With an enum, you write if (day == WEDNESDAY), and the code explains itself.
In this lesson you will create enumerations, see how C numbers their values, set your own values, use enums with switch, and compare enum with #define.
What You Will Learn
- What an enum is and why it helps.
- How to declare an enum and its variables.
- Default values (0, 1, 2…) and custom values.
- How to use enums with switch.
- The difference between enum and #define.
What is enum in C?
Exam definition: An enumeration (enum) is a user-defined data type that consists of a set of named integer constants called enumerators. By default, the first enumerator is 0 and each next one is one more than the previous.
Memory trick: An enum is like the floor buttons in a lift: "Ground, First, Second…" are names, but inside the lift they are just numbers 0, 1, 2. You press names; the machine uses numbers.
Syntax of enum
enum weekday { MON, TUE, WED, THU, FRI, SAT, SUN };
/* 0 1 2 3 4 5 6 */
enum weekday today = WED; /* today holds 2 */
enum level { LOW = 1, MEDIUM, HIGH = 10, CRITICAL };
/* 1 2 10 11 */
typedef enum { RED, YELLOW, GREEN } Signal; /* with typedef */
Signal s = GREEN;
- Enumerator names are usually written in CAPITALS, like other constants.
- A value without
=is previous + 1. - Two enumerators may have the same value, but two can't have the same name in one scope.
- Enumerators are really
intconstants, so they print with%d.
Example 1: Default and Custom enum Values
#include <stdio.h>
enum weekday { MON, TUE, WED, THU, FRI, SAT, SUN };
enum level { LOW = 1, MEDIUM, HIGH = 10, CRITICAL };
int main(void)
{
enum weekday today = FRI;
enum weekday d;
const char *names[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
printf("MON = %d, WED = %d, SUN = %d\n", MON, WED, SUN);
printf("LOW = %d, MEDIUM = %d, HIGH = %d, CRITICAL = %d\n",
LOW, MEDIUM, HIGH, CRITICAL);
printf("Today is %s (value %d)\n", names[today], today);
printf("Weekend? %s\n", (today == SAT || today == SUN) ? "yes" : "no");
printf("Working days:");
for (d = MON; d <= FRI; d++)
printf(" %s", names[d]);
printf("\n");
printf("sizeof(enum weekday) = %zu\n", sizeof(enum weekday));
return 0;
}
Output
MON = 0, WED = 2, SUN = 6 LOW = 1, MEDIUM = 2, HIGH = 10, CRITICAL = 11 Today is Fri (value 4) Weekend? no Working days: Mon Tue Wed Thu Fri sizeof(enum weekday) = 4
Code Explanation
- The weekday enumerators get 0 to 6 automatically.
- In
level,MEDIUMfollowsLOW = 1so it's 2;CRITICALfollowsHIGH = 10so it's 11. - Because enumerators are integers,
names[today]uses the enum as an array index: a handy way to print names. - The loop
for (d = MON; d <= FRI; d++)works since enum values are consecutive integers. - An enum variable is usually the size of an
int(4 bytes).
How enum Makes Code Safer and Clearer
- Readable:
state = PAIDis clearer thanstate = 2. - Grouped: related constants live together in one type.
- Debugger-friendly: debuggers can show
WEDinstead of 2. - Switch-friendly: compilers can warn when a
switchon an enum misses a case (-Wall). - Note: C does not stop you from storing any int in an enum variable (
today = 42;compiles). Enums help clarity; they are not strict.
Example 2: Traffic Signal Using enum and switch
#include <stdio.h>
typedef enum { RED, YELLOW, GREEN } Signal;
Signal next_signal(Signal s)
{
switch (s)
{
case RED: return GREEN;
case GREEN: return YELLOW;
case YELLOW: return RED;
}
return RED;
}
const char *action(Signal s)
{
switch (s)
{
case RED: return "Stop";
case YELLOW: return "Get ready";
case GREEN: return "Go";
}
return "?";
}
int main(void)
{
Signal s = RED;
int i;
for (i = 0; i < 4; i++)
{
printf("Signal %d: %s\n", s, action(s));
s = next_signal(s);
}
return 0;
}
Output
Signal 0: Stop Signal 2: Go Signal 1: Get ready Signal 0: Stop
case RED:is far clearer thancase 0:.typedef enum {...} Signal;lets us writeSignalinstead ofenum signal.- Printing
swith%dshows the underlying number (RED 0, GREEN 2, YELLOW 1).
enum vs #define
| Point | enum | #define |
|---|---|---|
| Handled by | Compiler | Preprocessor |
| Values | Assigned automatically (0, 1, 2…) | Each written by hand |
| Grouping | Related names form one type | Separate, unrelated macros |
| Scope | Follows block scope | Global from the line onwards |
| Types allowed | Integers only | Any value (float, string…) |
| Debugging | Names visible in the debugger | Replaced before compiling |
Important Points to Remember
- An enum is a set of named integer constants.
- Default values start at 0 and go up by 1.
- A value without
=is previous + 1. - Enumerators print with %d; size is usually that of an int.
- Great with switch and as array indexes.
- Enum values must be integers; names must be unique in a scope.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
| Expecting the first value to be 1 | Off-by-one errors | Default starts at 0 (or write = 1) |
printf("%s", WED) | Crash: WED is an int | Use a names array or switch |
Same enumerator in two enums: enum a {OK}; enum b {OK}; | Error: redeclaration | Use different names (A_OK, B_OK) |
enum rate {HALF = 0.5}; | Error: not an integer | Use a const double or #define |
Missing semicolon after } | Compile error | Write }; |
enum Practice Questions
- Define an enumeration.
- What are the values in
enum c {A, B = 5, C, D = 2, E};? - What is the default value of the first enumerator?
- Give three differences between enum and #define.
- Can enum values be floating-point numbers?
Show answers
- A user-defined type made of named integer constants (enumerators).
- A = 0, B = 5, C = 6, D = 2, E = 3.
- 0.
- enum is handled by the compiler, #define by the preprocessor; enum assigns values automatically; enum groups constants into one type and follows scope rules.
- No, only integers.
Coding Exercise
Create enum month {JAN = 1, FEB, ..., DEC}. Write a function that returns the number of days in a month (ignore leap years) using a switch on the enum, and print days for FEB, APR and DEC.
Show solution
#include <stdio.h>
enum month { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };
int days_in(enum month m)
{
switch (m)
{
case FEB:
return 28;
case APR: case JUN: case SEP: case NOV:
return 30;
default:
return 31;
}
}
int main(void)
{
printf("FEB (%d): %d days\n", FEB, days_in(FEB));
printf("APR (%d): %d days\n", APR, days_in(APR));
printf("DEC (%d): %d days\n", DEC, days_in(DEC));
return 0;
}
FEB (2): 28 days APR (4): 30 days DEC (12): 31 days
Quick Quiz: enum in C (MCQ)
-
In
enum {X, Y, Z};, Z is:A) 1 B) 2 C) 3 D) 0
-
In
enum {P = 4, Q, R = 1, S};, S is:A) 5 B) 2 C) 6 D) 0
-
Enumerators are constants of type:
A) float B) char * C) int D) double
-
Which is handled by the compiler?
A)
#defineB)enumC)#includeD)#ifdef -
Format specifier to print an enum value:
A)
%sB)%dC)%eD)%c
Show answers
- B: 2.
- B: 2 (R = 1, so S = 2).
- C: int.
- B:
enum. - B:
%d.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| enum | Set of named integer constants |
|---|---|
| Default start | 0, then +1 |
| No = given | previous + 1 |
| Type of enumerators | int (print with %d) |
| Best used with | switch, array indexes, states |
| vs #define | enum = compiler, grouped, auto values |
Frequently asked questions
- What is enum in C?
- A user-defined type of named integer constants, starting at 0 by default.
- What is the difference between enum and #define?
- enum is handled by the compiler, gives automatic values and groups names; #define is text replacement, one value at a time.
- Can two enum constants have the same value?
- Yes, values can repeat, but names must be unique.
Remember
- enum = lift buttons: names outside, numbers inside.
- Starts at 0 unless you say otherwise.
Next Topic
Next lesson: Bit Fields in C. You will pack several small values into a few bits with bit fields.