๐ค 20. Enumerations (enum) and typedef
Think of this topic as two tools with different jobs: enum gives meaningful names to a fixed set of choices, while typedef gives a convenient alias to an existing type. First understand the idea, then learn the declaration pattern, then use it in real programs.
An enumeration creates named integer constants for a related set of choices.
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
};
Instead of writing unexplained numbers such as 0, 1, and 2, the program can use names such as SUNDAY, MONDAY, and TUESDAY.
It makes the meaning of a value visible in the source code. That is especially useful for states, menu choices, days, directions, modes, and status values.
20.2 The enum Value Model
By default, the first enumerator has value 0, and each following enumerator increases by 1.
| Name | Value |
|---|---|
| SUNDAY | 0 |
| MONDAY | 1 |
| TUESDAY | 2 |
| WEDNESDAY | 3 |
| THURSDAY | 4 |
| FRIDAY | 5 |
| SATURDAY | 6 |
20.3 Declaring and Using an enum Variable
enum Day today;
today = MONDAY;
You can also initialize the variable when declaring it:
enum Day today = MONDAY;
The important distinction is:
Defines the enumeration type.
Names one enumerator value.
Is the actual variable.
20.4 Explicit enum Values
You can assign specific integer values when the program needs meaningful codes.
enum Status {
FAILURE = 0,
SUCCESS = 1
};
This is useful when the values have a defined meaning in the program or an external interface.
20.5 Mixed enum Values โ The Rule You Must Remember
enum Numbers {
A = 10,
B,
C,
D = 20,
E
};
| Enumerator | Value | Why? |
|---|---|---|
| A | 10 | Explicitly assigned |
| B | 11 | Previous value + 1 |
| C | 12 | Previous value + 1 |
| D | 20 | Explicitly assigned |
| E | 21 | Previous value + 1 |
20.6 enum with switch โ A Natural Combination
Enums are particularly readable when a program must choose an action for one of several named states.
#include <stdio.h>
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
int main(void)
{
enum Day day = WEDNESDAY;
switch (day)
{
case SUNDAY: printf("Sunday"); break;
case MONDAY: printf("Monday"); break;
case TUESDAY: printf("Tuesday"); break;
case WEDNESDAY: printf("Wednesday"); break;
case THURSDAY: printf("Thursday"); break;
case FRIDAY: printf("Friday"); break;
case SATURDAY: printf("Saturday"); break;
}
return 0;
}
20.7 enum as a State Model
An enum becomes especially useful when a variable represents the current state of a system.
enum Status {
PENDING,
APPROVED,
REJECTED
};
20.8 Real-Life Example โ Traffic Light
enum TrafficLight { RED, YELLOW, GREEN };
enum TrafficLight light = GREEN;
if (light == RED)
printf("STOP");
else if (light == YELLOW)
printf("READY");
else
printf("GO");
20.9 enum Comparisons
Because enumerators represent integer constants, comparisons such as the following are possible:
enum TrafficLight light = GREEN;
if (light == GREEN) {
printf("GO");
}
GREEN is an enumerator name. Its numeric value is determined by the enum declaration. Use the name when writing readable application logic.20.10 enum Size and Representation
The size and representation of an enum object are implementation-defined. Therefore, portable C code should not assume that every enum occupies exactly 4 bytes.
printf("%zu\n", sizeof(enum TrafficLight));
20.11 What Is typedef?
typedef creates an alias, or alternative name, for an existing type.
typedef int Number;
Number age = 20;
Number is not a new variable and does not allocate storage by itself. It is simply another name for the type int.
20.12 Basic typedef Pattern
intNumberNumber x;typedef unsigned int UINT;
UINT count = 100;
20.13 typedef with Structure
One of the most common uses of typedef is making structure declarations shorter.
Without typedef:
struct Student {
int id;
char name[50];
};
struct Student s;
With typedef:
typedef struct {
int id;
char name[50];
} Student;
Student s;
20.14 Complete typedef Structure Example
#include <stdio.h>
typedef struct {
int id;
char name[50];
float marks;
} Student;
int main(void)
{
Student s = {101, "Venu", 85.5f};
printf("ID = %d\n", s.id);
printf("Name = %s\n", s.name);
printf("Marks = %.2f\n", s.marks);
return 0;
}
Name = Venu
Marks = 85.50
20.15 typedef with enum
You can combine the two ideas so the enum type itself has a convenient name.
typedef enum {
LOW,
MEDIUM,
HIGH
} Level;
Level current = HIGH;
Now you write Level instead of enum Level.
20.16 typedef with Pointer
typedef int *IntPtr;
int x = 10;
IntPtr p = &x;
Here IntPtr is an alias for int *.
20.17 Why Pointer typedef Can Be Useful
typedef int *IntPtr;
IntPtr p1, p2;
Both p1 and p2 are pointers to int.
Compare that with the normal declaration:
int *p1, p2;
Only p1 is a pointer; p2 is an ordinary int.
* is part of the alias. Always read the typedef declaration before declaring variables.20.18 typedef with an Array
typedef int Marks[5];
Marks studentMarks;
studentMarks[0] = 90;
Marks is now an alias for โarray of 5 intโ.
20.19 typedef with a Function Pointer
Function-pointer declarations can become difficult to read. typedef can give the function-pointer type a meaningful name.
typedef int (*Operation)(int, int);
Operation op;
Read the alias as: Operation is a pointer to a function that takes two ints and returns int.
20.20 Complete Function-Pointer typedef Example
#include <stdio.h>
typedef int (*Operation)(int, int);
int add(int a, int b)
{
return a + b;
}
int main(void)
{
Operation op = add;
printf("%d\n", op(10, 20));
return 0;
}
20.21 typedef Does Not Create a New Variable
typedef int Number;
This statement only introduces an alias. A variable is created only when you declare one:
Number x = 10;
typedef itself does not allocate memory for an object.20.22 typedef vs #define
| typedef | #define |
|---|---|
| Creates a type alias | Performs preprocessor text substitution |
| Part of C's type system | Handled before normal compilation |
| Useful for simplifying declarations | Useful for macros and symbolic substitutions |
| Understood as a type declaration | Does not create a C type |
typedef unsigned long Size;
#define MAX_SIZE 100
Here Size is a type alias, while MAX_SIZE is a macro.
20.23 enum vs typedef โ Different Jobs
| enum | typedef |
|---|---|
| Defines named enumerator constants | Creates an alias for an existing type |
| Models a fixed set of choices | Simplifies type declarations |
Example: RED, GREEN, BLUE | Example: typedef int Number; |
What problem are you solving?
Use
enum.Consider
typedef.20.24 Using enum and typedef Together
typedef enum {
PENDING,
APPROVED,
REJECTED
} Status;
typedef struct {
int id;
Status status;
} Application;
Application app = {1001, APPROVED};
This pattern is common in larger C programs because the data model becomes self-explanatory.
20.25 Real-Life Student Example
#include <stdio.h>
typedef enum {
FAIL,
PASS
} Result;
typedef struct {
int id;
char name[50];
float marks;
Result result;
} Student;
int main(void)
{
Student s = {101, "Venu", 78.5f, PASS};
printf("ID = %d\n", s.id);
printf("Name = %s\n", s.name);
printf("Marks = %.1f\n", s.marks);
printf("Result = %s\n", s.result == PASS ? "PASS" : "FAIL");
return 0;
}
Name = Venu
Marks = 78.5
Result = PASS
20.26 Common enum Mistakes
Default numbering starts at 0.
Its size is implementation-defined.
Prefer meaningful enumerator names when choices have domain meaning.
Consider all meaningful states and a
default when appropriate.20.27 Common typedef Mistakes and Placement Rules
It creates an alias only.
One is a type alias; the other is preprocessing substitution.
typedef int *IntPtr; makes the pointer part of the alias.A typedef should make a declaration clearer, not more mysterious.
fixed named choices
type alias
states + clean declarations
enum answers โWhich named choice is this?โ and typedef answers โWhat convenient name should I use for this type?โ. Do not use either just to make code shorter; use them when they make the program's meaning clearer.
20.28 Quick Revision
๐ First enum value is normally 0
๐ Enum values can be explicitly assigned
๐ typedef โ Creates a type alias
๐ typedef does not create a new variable
๐ typedef is commonly used with structures
๐ typedef can simplify pointer declarations
๐ typedef can be used with enum, arrays and function pointers
๐ #define performs preprocessor text substitution
๐ฌ Enumerations & typedef โ Type Design Flow
Follow how readable fixed choices are created with enum
and how typedef simplifies type names.
๐ฌ enum + typedef Visualizer
๐ Program Tracing โ Enumerations & typedef
Trace a typedef enum, an enum variable, its integer value,
and selection through switch.
โ
20.29 Quick MCQs
Select an answer first, then click Check Answer. A correct choice becomes green. If the answer is wrong, your choice becomes red and the correct option becomes green. The explanation appears below.
enum is used to define a set of named integer constants.
Unless a value is specified, the first enumerator is 0.
typedef creates an alias for an existing type.
typedef introduces a type name; it does not declare an object by itself.
typedef is commonly combined with struct declarations to create cleaner type names.
#define is a preprocessing directive for macro substitution.
typedef int Number; makes Number an alias for int.
typedef int* IntPtr; creates IntPtr as an alias for pointer-to-int.
typedef is especially useful for simplifying function-pointer declarations.
Enums improve readability for fixed sets of related values.
20.30 ๐ฏ Practice Problems
Practice enum values, switch with enums, typedef aliases, structures, pointers, arrays, function pointers, and combined designs. Use ๐ป Solve It Yourself first, open Hint only when needed, and use Show Program after attempting the problem.
Problem 1: Create an enum representing the seven days of the week and print the value of WEDNESDAY.
Input: No input.
Output: Print 3 when SUNDAY starts at 0.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
enum Day
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
};
int main()
{
printf("%d", WEDNESDAY);
return 0;
}
Problem 2: Print the integer value of each day in an enum from SUNDAY to SATURDAY.
Input: No input.
Output: Print seven lines in the form NAME=value.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
int main()
{
printf("SUNDAY=%d\n", SUNDAY);
printf("MONDAY=%d\n", MONDAY);
printf("TUESDAY=%d\n", TUESDAY);
printf("WEDNESDAY=%d\n", WEDNESDAY);
printf("THURSDAY=%d\n", THURSDAY);
printf("FRIDAY=%d\n", FRIDAY);
printf("SATURDAY=%d", SATURDAY);
return 0;
}
Problem 3: Create an enum for RED, YELLOW and GREEN traffic lights and print GREEN's value.
Input: No input.
Output: Print 2.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
enum TrafficLight { RED, YELLOW, GREEN };
int main()
{
printf("%d", GREEN);
return 0;
}
Problem 4: Read an integer from 0 to 6, convert it to an enum Day value, and display the corresponding day name using switch.
Input: One integer from 0 to 6.
Output: Print the corresponding uppercase day name.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
int main()
{
int value;
scanf("%d", &value);
enum Day day = (enum Day)value;
switch (day)
{
case SUNDAY: printf("SUNDAY"); break;
case MONDAY: printf("MONDAY"); break;
case TUESDAY: printf("TUESDAY"); break;
case WEDNESDAY: printf("WEDNESDAY"); break;
case THURSDAY: printf("THURSDAY"); break;
case FRIDAY: printf("FRIDAY"); break;
case SATURDAY: printf("SATURDAY"); break;
default: printf("INVALID");
}
return 0;
}
Problem 5: Create an enum with custom values 10, 20 and 30 and print them.
Input: No input.
Output: Print 10 20 30.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
enum Code { FIRST = 10, SECOND = 20, THIRD = 30 };
int main()
{
printf("%d %d %d", FIRST, SECOND, THIRD);
return 0;
}
Problem 6: Create an enum for FAIL, PASS and DISTINCTION, read a value 0/1/2, and print the matching label.
Input: One integer 0, 1 or 2.
Output: Print FAIL, PASS or DISTINCTION.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
enum Result { FAIL, PASS, DISTINCTION };
int main()
{
int value;
scanf("%d", &value);
switch ((enum Result)value)
{
case FAIL: printf("FAIL"); break;
case PASS: printf("PASS"); break;
case DISTINCTION: printf("DISTINCTION"); break;
default: printf("INVALID");
}
return 0;
}
Problem 7: Create an enum representing ADMIN, TEACHER and STUDENT and display the role selected by a number.
Input: One integer 0, 1 or 2.
Output: Print ADMIN, TEACHER or STUDENT.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
enum Role { ADMIN, TEACHER, STUDENT };
int main()
{
int value;
scanf("%d", &value);
switch ((enum Role)value)
{
case ADMIN: printf("ADMIN"); break;
case TEACHER: printf("TEACHER"); break;
case STUDENT: printf("STUDENT"); break;
default: printf("INVALID");
}
return 0;
}
Problem 8: Use typedef to create an alias Number for int, read one integer, and print it.
Input: One integer.
Output: Print the same integer.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
typedef int Number;
int main()
{
Number value;
scanf("%d", &value);
printf("%d", value);
return 0;
}
Problem 9: Use typedef to create UInt as an alias for unsigned int and print a value.
Input: One unsigned integer.
Output: Print the same value.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
typedef unsigned int UInt;
int main()
{
UInt value;
scanf("%u", &value);
printf("%u", value);
return 0;
}
Problem 10: Create a typedef structure for Student with roll number and marks, read one student, and print the fields.
Input: Roll number and marks.
Output: Print roll and marks.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
typedef struct
{
int roll;
float marks;
} Student;
int main()
{
Student s;
scanf("%d %f", &s.roll, &s.marks);
printf("%d %.1f", s.roll, s.marks);
return 0;
}
Problem 11: Create a typedef structure for Employee containing id and salary.
Input: Employee id and salary.
Output: Print id and salary to two decimal places.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
typedef struct
{
int id;
double salary;
} Employee;
int main()
{
Employee e;
scanf("%d %lf", &e.id, &e.salary);
printf("%d %.2f", e.id, e.salary);
return 0;
}
Problem 12: Create a typedef for an integer pointer, point it to a variable, and print the value through the alias.
Input: One integer.
Output: Print the integer through the pointer.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
typedef int *IntPtr;
int main()
{
int value;
scanf("%d", &value);
IntPtr p = &value;
printf("%d", *p);
return 0;
}
Problem 13: Create a typedef for an array of 10 integers, read 10 values, and print their sum.
Input: Ten integers.
Output: Print the sum.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
typedef int IntArray10[10];
int main()
{
IntArray10 a;
int sum = 0;
for (int i = 0; i < 10; i++)
{
scanf("%d", &a[i]);
sum += a[i];
}
printf("%d", sum);
return 0;
}
Problem 14: Create a typedef for a function pointer that adds two integers and call it.
Input: Two integers.
Output: Print their sum.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
typedef int (*Operation)(int, int);
int add(int a, int b)
{
return a + b;
}
int main()
{
int a, b;
scanf("%d %d", &a, &b);
Operation op = add;
printf("%d", op(a, b));
return 0;
}
Problem 15: Create a Student structure containing an enum Result field and display the stored result.
Input: Roll number and result value 0/1/2.
Output: Print roll and result label.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
enum Result { FAIL, PASS, DISTINCTION };
struct Student
{
int roll;
enum Result result;
};
int main()
{
struct Student s;
int value;
scanf("%d %d", &s.roll, &value);
s.result = (enum Result)value;
printf("%d ", s.roll);
switch (s.result)
{
case FAIL: printf("FAIL"); break;
case PASS: printf("PASS"); break;
case DISTINCTION: printf("DISTINCTION"); break;
default: printf("INVALID");
}
return 0;
}
Problem 16: Create a typedef enum representing ACTIVE, BLOCKED and CLOSED and print the selected label.
Input: One integer 0, 1 or 2.
Output: Print ACTIVE, BLOCKED or CLOSED.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
typedef enum { ACTIVE, BLOCKED, CLOSED } AccountStatus;
int main()
{
int value;
scanf("%d", &value);
AccountStatus status = (AccountStatus)value;
switch (status)
{
case ACTIVE: printf("ACTIVE"); break;
case BLOCKED: printf("BLOCKED"); break;
case CLOSED: printf("CLOSED"); break;
default: printf("INVALID");
}
return 0;
}
Problem 17: Create a typedef structure for a bank account and use an enum for account status.
Input: Account number, balance, status 0/1/2.
Output: Print account number, balance and status.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
typedef enum { ACTIVE, BLOCKED, CLOSED } AccountStatus;
typedef struct
{
int number;
double balance;
AccountStatus status;
} BankAccount;
const char *statusName(AccountStatus status)
{
switch (status)
{
case ACTIVE: return "ACTIVE";
case BLOCKED: return "BLOCKED";
case CLOSED: return "CLOSED";
default: return "INVALID";
}
}
int main()
{
BankAccount account;
int status;
scanf("%d %lf %d", &account.number, &account.balance, &status);
account.status = (AccountStatus)status;
printf("%d %.2f %s", account.number, account.balance, statusName(account.status));
return 0;
}
Problem 18: Create a typedef function pointer that can call multiplication and integer division operations.
Input: Two integers followed by operation 1 for multiply or 2 for divide. Divisor is non-zero for division tests.
Output: Print the selected result.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
typedef int (*Operation)(int, int);
int multiply(int a, int b) { return a * b; }
int divideInt(int a, int b) { return a / b; }
int main()
{
int a, b, choice;
scanf("%d %d %d", &a, &b, &choice);
Operation op = (choice == 1) ? multiply : divideInt;
printf("%d", op(a, b));
return 0;
}
Problem 19: Create an array of Student records using typedef and enum, then count how many students passed or achieved distinction.
Input: n followed by n records: roll marks. Result is derived as FAIL <50, PASS 50-74, DISTINCTION >=75.
Output: Print Passed = count.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
typedef enum { FAIL, PASS, DISTINCTION } Result;
typedef struct
{
int roll;
int marks;
Result result;
} Student;
int main()
{
int n;
scanf("%d", &n);
Student students[n];
int passed = 0;
for (int i = 0; i < n; i++)
{
scanf("%d %d", &students[i].roll, &students[i].marks);
if (students[i].marks >= 75)
students[i].result = DISTINCTION;
else if (students[i].marks >= 50)
students[i].result = PASS;
else
students[i].result = FAIL;
if (students[i].result != FAIL)
passed++;
}
printf("Passed = %d", passed);
return 0;
}
Problem 20: Create a complete Employee Management program using typedef struct and enums for department and employment status, then print each employee.
Input: n followed by n records: id department status salary. Department: 0=HR,1=TECH,2=SALES. Status: 0=ACTIVE,1=ON_LEAVE,2=INACTIVE.
Output: Print one employee per line with readable department and status labels.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
typedef enum { HR, TECH, SALES } Department;
typedef enum { ACTIVE, ON_LEAVE, INACTIVE } EmploymentStatus;
typedef struct
{
int id;
Department department;
EmploymentStatus status;
double salary;
} Employee;
const char *departmentName(Department d)
{
switch (d)
{
case HR: return "HR";
case TECH: return "TECH";
case SALES: return "SALES";
default: return "INVALID";
}
}
const char *statusName(EmploymentStatus s)
{
switch (s)
{
case ACTIVE: return "ACTIVE";
case ON_LEAVE: return "ON_LEAVE";
case INACTIVE: return "INACTIVE";
default: return "INVALID";
}
}
int main()
{
int n;
scanf("%d", &n);
Employee employees[n];
for (int i = 0; i < n; i++)
{
int department, status;
scanf("%d %d %d %lf",
&employees[i].id,
&department,
&status,
&employees[i].salary);
employees[i].department = (Department)department;
employees[i].status = (EmploymentStatus)status;
}
for (int i = 0; i < n; i++)
{
if (i > 0)
printf("\n");
printf("%d %s %s %.2f",
employees[i].id,
departmentName(employees[i].department),
statusName(employees[i].status),
employees[i].salary);
}
return 0;
}
20.31 Key Takeaway
enum โ Give names to related integer constants.
typedef โ Give an existing type a convenient alias.
enum + switch โ Excellent combination for fixed choices.
typedef + struct โ Cleaner structure declarations.
typedef + pointer โ Can simplify pointer declarations.
typedef + function pointer โ Makes complex declarations easier.
#define โ typedef.
๐ค Enumerations & typedef โ Interview Questions
๐ก Enumerations & typedef โ Placement Tips
- Use
enumwhen a variable should represent one value from a fixed, meaningful set of choices. - Remember that default enum values begin at
0and increase by1unless you assign explicit values. typedefcreates a type alias; it does not allocate memory or create a variable.typedef struct {{ ... }} Name;is a common pattern for cleaner structure declarations.- Function-pointer typedefs are especially valuable because they make callback and operation declarations easier to read.
- Do not confuse
typedefwith#define: one works with C types, while the other performs preprocessing substitution.
โ๏ธ Enumerations & typedef โ Extra Practice Questions
- Create an enum for months and print the number of days for a selected month using switch.
- Create a typedef enum for menu states such as START, SETTINGS, HELP and EXIT.
- Create a typedef structure for a book with a genre enum.
- Create a function-pointer typedef for comparison functions and use it to choose ascending or descending comparison.
- Create a typedef for a pointer to a Student structure and use it to modify student marks.
- Design a small order-management structure combining enums for order status and payment status.