๐Ÿ”ค 20. Enumerations (enum) and typedef

๐ŸŽ“ How to Learn This Topic

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.

20.1 What Is an enum?

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.

Why use it?
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.

NameValue
SUNDAY0
MONDAY1
TUESDAY2
WEDNESDAY3
THURSDAY4
FRIDAY5
SATURDAY6
Placement point: The names are integer constants. The standard does not require the enum object itself to have one particular size or representation.

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:

enum Day
Defines the enumeration type.
MONDAY
Names one enumerator value.
today
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
};
EnumeratorValueWhy?
A10Explicitly assigned
B11Previous value + 1
C12Previous value + 1
D20Explicitly assigned
E21Previous 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;
}
Wednesday

20.7 enum as a State Model

An enum becomes especially useful when a variable represents the current state of a system.

State
PENDING
Work has not finished.
โ†’
State
APPROVED
The request was accepted.
โ†’
State
REJECTED
The request was declined.
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");
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");
}
Do not confuse name and value: 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));
Interview point: Default enumerator values are predictable, but the storage size of an enum object is not something portable code should hard-code.

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

Existing type
int
โ†’
typedef alias
Number
โ†’
Declaration
Number 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;
Why this is useful: The data model remains a structure, but every variable declaration becomes easier to read.

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;
}
ID = 101
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.

Common trap: With pointer typedefs, the * 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;
}
30

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;
Memory rule: typedef itself does not allocate memory for an object.

20.22 typedef vs #define

typedef#define
Creates a type aliasPerforms preprocessor text substitution
Part of C's type systemHandled before normal compilation
Useful for simplifying declarationsUseful for macros and symbolic substitutions
Understood as a type declarationDoes 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

enumtypedef
Defines named enumerator constantsCreates an alias for an existing type
Models a fixed set of choicesSimplifies type declarations
Example: RED, GREEN, BLUEExample: typedef int Number;
Question
What problem are you solving?
Fixed choices?
Use enum.
Long or awkward type name?
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;
}
ID = 101
Name = Venu
Marks = 78.5
Result = PASS

20.26 Common enum Mistakes

โŒ Assuming every enum starts at 1
Default numbering starts at 0.
โŒ Assuming enum size is always 4 bytes
Its size is implementation-defined.
โŒ Using magic numbers
Prefer meaningful enumerator names when choices have domain meaning.
โŒ Forgetting switch coverage
Consider all meaningful states and a default when appropriate.

20.27 Common typedef Mistakes and Placement Rules

typedef is not a variable
It creates an alias only.
typedef is not #define
One is a type alias; the other is preprocessing substitution.
Read pointer aliases carefully
typedef int *IntPtr; makes the pointer part of the alias.
Use meaningful aliases
A typedef should make a declaration clearer, not more mysterious.
enum
fixed named choices
+
typedef
type alias
=
Readable data model
states + clean declarations
๐Ÿง  CodeBhavya Rule

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

๐Ÿ“Œ enum โ†’ Named integer constants

๐Ÿ“Œ 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
INTERACTIVE LEARNING

๐ŸŽฌ Enumerations & typedef โ€” Type Design Flow

Follow how readable fixed choices are created with enum and how typedef simplifies type names.

PROGRAM TRACING

๐Ÿ”Ž 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.

1. What is enum used for?
2. What is the default value of the first enum constant?
3. Which keyword creates a type alias?
4. Does typedef create a new variable?
5. Which is commonly used with typedef?
6. Which performs preprocessor text substitution?
7. Which declaration creates an alias for int?
8. Which is a valid typedef pointer declaration?
9. Can typedef be used with a function pointer?
10. Which is the best reason to use enum?
PRACTICE

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.

๐Ÿ“ˆ Enumerations & typedef Practice Progress
Solved 0 / 20
Completed with Solution 0
Total Score 0 / 2000
Completion 0%
A problem counts as Solved when all test cases pass without opening the full solution. Problems completed after viewing the official solution are tracked separately.
1. Seven Days enum

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.

2. Print Integer Value of Every Day

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.

3. Traffic Light enum

Problem 3: Create an enum for RED, YELLOW and GREEN traffic lights and print GREEN's value.

Input: No input.

Output: Print 2.

4. enum with switch โ€” Day of Week

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.

5. Custom enum Values

Problem 5: Create an enum with custom values 10, 20 and 30 and print them.

Input: No input.

Output: Print 10 20 30.

6. Student Result enum

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.

7. User Role enum

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.

8. typedef Alias for int

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.

9. typedef Alias for unsigned int

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.

10. typedef Structure for Student

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.

11. typedef Structure for Employee

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.

12. typedef Integer Pointer

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.

13. typedef Array of 10 Integers

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.

14. typedef Function Pointer for Addition

Problem 14: Create a typedef for a function pointer that adds two integers and call it.

Input: Two integers.

Output: Print their sum.

15. Student Structure with enum Result

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.

16. typedef enum Account Status

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.

17. Bank Account with enum Status

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.

18. Function Pointer for Multiplication and Division

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.

19. Student Management with typedef and enum

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.

20. Employee Management with Department and Status

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.

20.31 Key Takeaway

๐ŸŽฏ Remember:

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.
INTERVIEW PREPARATION

๐ŸŽค Enumerations & typedef โ€” Interview Questions

1. What is an enum in C?
2. What value does the first enumerator receive by default?
3. Can enum values be assigned explicitly?
4. What does typedef do?
5. Why is typedef often used with struct?
6. Why can typedef with pointers be confusing?
7. Can typedef simplify function pointers?
8. What is the difference between typedef and #define?
PLACEMENT TIPS

๐Ÿ’ก Enumerations & typedef โ€” Placement Tips

  • Use enum when a variable should represent one value from a fixed, meaningful set of choices.
  • Remember that default enum values begin at 0 and increase by 1 unless you assign explicit values.
  • typedef creates 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 typedef with #define: one works with C types, while the other performs preprocessing substitution.
EXTRA PRACTICE

โœ๏ธ Enumerations & typedef โ€” Extra Practice Questions

  1. Create an enum for months and print the number of days for a selected month using switch.
  2. Create a typedef enum for menu states such as START, SETTINGS, HELP and EXIT.
  3. Create a typedef structure for a book with a genre enum.
  4. Create a function-pointer typedef for comparison functions and use it to choose ascending or descending comparison.
  5. Create a typedef for a pointer to a Student structure and use it to modify student marks.
  6. Design a small order-management structure combining enums for order status and payment status.
โ† Previous Topic: Bitwise Programming Next Topic: Operator Precedence & Associativity โ†’