SrcForge

Lesson 22

Enums and typedef

Enums in C define a set of named integer constants that replace magic numbers and improve readability. typedef creates an alias for an existing data type, simplifying long or complex declarations. Combining both results in cleaner, more maintainable code.

C Track

Save progress as you learn.

44 lessons

Lesson content

Enums and typedef in C Programming: A Complete Beginner to Advanced Guide

What are Enums and typedef in C Programming?

Enums and typedef in C programming are two language features that make code more readable, maintainable, and easier to understand.

An enum (short for enumeration) allows you to create a set of named integer constants. Instead of using meaningless numbers like 0, 1, or 2, you can use descriptive names such as RED, GREEN, and BLUE.

A typedef creates an alias (another name) for an existing data type. It helps simplify long or complex type declarations and improves code readability.

Think of it like giving nicknames: an enum gives meaningful names to fixed integer values, while a typedef gives a simpler name to an existing data type.

Why Do Enums and typedef Exist?

Without enums and typedef, programs often contain magic numbers that are difficult to understand, long and repetitive type declarations, and code that is harder to read and maintain. These features solve those problems by making code self-explanatory.

Real-World Use Cases

Enums and typedef are widely used in:

  • Game development (game states)
  • Embedded systems (device modes)
  • Network programming (packet types)
  • Operating systems
  • Device drivers
  • Menu-driven applications
  • Library and API development

Prerequisites

Before learning Enums and typedef in C, you should know:

  • Variables
  • Data types
  • Constants
  • Functions
  • Basic syntax
  • Structures (helpful but optional)

Core Concepts

What is an Enum?

An enum is a user-defined data type consisting of a fixed set of named integer constants.

Syntax

enum EnumName
{
    CONSTANT1,
    CONSTANT2,
    CONSTANT3
};

By default, values are assigned starting from 0 and increment automatically:

ConstantValue
CONSTANT10
CONSTANT21
CONSTANT32

Assigning Custom Values

You can assign your own integer values. Subsequent constants continue counting from the assigned value.

enum Day
{
    MON = 1,
    TUE,
    WED,
    THU
};
ConstantValue
MON1
TUE2
WED3
THU4

What is typedef?

A typedef creates another name (alias) for an existing data type.

Syntax

typedef existing_type new_name;
typedef unsigned int uint;

Now instead of writing unsigned int age, you can write:

uint age;

typedef with Structures

One of the most common uses of typedef is with structures.

Without typedef:

struct Student
{
    int id;
};

struct Student s1;

With typedef:

typedef struct
{
    int id;
} Student;

Student s1;

Combining enum and typedef

Many C programmers combine both to produce cleaner declarations.

typedef enum
{
    OFF,
    ON
} SwitchState;

SwitchState state = ON;

Code Examples

Example 1: Beginner – Basic Enum

#include <stdio.h>                     // Include standard input/output library

enum Color                            // Declare enum
{
    RED,                              // Value 0
    GREEN,                            // Value 1
    BLUE                              // Value 2
};

int main(void)
{
    enum Color color = GREEN;         // Create enum variable

    printf("%d\n", color);            // Print integer value

    return 0;                         // End program
}

Output: 1

Example 2: Beginner – Enum with Custom Values

#include <stdio.h>                    // Include standard input/output library

enum Status                           // Declare enum
{
    SUCCESS = 200,                    // Assign custom value
    NOT_FOUND = 404,                  // Assign custom value
    SERVER_ERROR = 500                // Assign custom value
};

int main(void)
{
    printf("%d\n", SUCCESS);          // Print SUCCESS value

    printf("%d\n", NOT_FOUND);        // Print NOT_FOUND value

    return 0;                         // End program
}

Output: 200 / 404

Example 3: Intermediate – Using typedef

#include <stdio.h>                    // Include standard input/output library

typedef unsigned long ulong;          // Create type alias

int main(void)
{
    ulong population = 1450000000;    // Declare variable using alias

    printf("%lu\n", population);      // Print value

    return 0;                         // End program
}

Output: 1450000000

Example 4: Intermediate – typedef with Structure

#include <stdio.h>                    // Include standard input/output library

typedef struct                        // Define structure and alias
{
    int rollNo;                       // Student roll number
    float marks;                      // Student marks
} Student;

int main(void)
{
    Student s1;                       // Create structure variable

    s1.rollNo = 101;                  // Assign roll number
    s1.marks = 92.5f;                 // Assign marks

    printf("%d %.1f\n", s1.rollNo, s1.marks); // Display data

    return 0;                         // End program
}

Output: 101 92.5

Example 5: Advanced – Combining enum and typedef

#include <stdio.h>                         // Include standard input/output library

typedef enum                               // Create enum alias
{
    LOW,                                   // Priority level 0
    MEDIUM,                                // Priority level 1
    HIGH                                   // Priority level 2
} Priority;

int main(void)
{
    Priority task = HIGH;                  // Create enum variable

    if (task == HIGH)                      // Check priority
    {
        printf("High Priority Task\n");    // Display message
    }

    return 0;                              // End program
}

Output: High Priority Task

Common Mistakes and Pitfalls

WrongCorrect
typedef int;typedef int Integer;
Using enum values before declaring the enumDeclare the enum first, then use its constants
Assuming enum values are stringsEnum constants are integer values by default
Giving duplicate aliases that confuse readersChoose clear, descriptive alias names
Using typedef to create a new data typetypedef creates only an alias, not a new type

Wrong:

typedef int;

Correct:

typedef int Integer;

Wrong:

enum Status s;

enum Status
{
    ON,
    OFF
};

Correct:

enum Status
{
    ON,
    OFF
};

enum Status s;

Best Practices

  • Use enums instead of magic numbers whenever values represent fixed states.
  • Use meaningful names for enum constants, such as FILE_OPEN or CONNECTION_FAILED.
  • Keep related constants within the same enum.
  • Use typedef to simplify long type declarations.
  • Prefer typedef with structures, unions, and function pointers to improve readability.
  • Avoid creating too many aliases for basic data types, as this can make code harder to understand.
  • Use uppercase names for enum constants to distinguish them from variables.

When NOT to Use This

Avoid enums when:

  • Values need to change at runtime.
  • You need floating-point values, as enums can only represent integer constants.
  • A large number of unrelated constants would make the enum difficult to manage.

Avoid typedef when:

  • The alias hides important details of a type.
  • It makes simple types less recognizable (for example, renaming int to something unusual).
  • The alias reduces code clarity rather than improving it.

Summary / Key Takeaways

  • Enums in C programming define a set of named integer constants.
  • Enum values start at 0 by default unless explicitly assigned.
  • typedef creates an alias for an existing data type.
  • typedef does not create a new type; it simply provides another name.
  • typedef is commonly used with structures, unions, and function pointers.
  • Combining enum and typedef results in cleaner, more readable code.
  • Use enums to replace magic numbers and improve code maintainability.
  • Choose descriptive names for both enum constants and typedef aliases.

FAQ About Enums and typedef in C

1. What is an enum in C programming?

An enum is a user-defined data type that contains a collection of named integer constants, making code easier to read and maintain.

2. What is typedef in C?

typedef is a keyword that creates an alias for an existing data type, reducing the need to write long type names repeatedly.

3. Does typedef create a new data type?

No. typedef only creates another name for an existing type. It does not create a completely new type.

4. Can enum values be assigned manually?

Yes. You can assign any integer value to an enum constant, and subsequent constants continue counting from that value unless specified otherwise.

enum Level
{
    LOW = 10,
    MEDIUM,
    HIGH
};

Here, MEDIUM becomes 11 and HIGH becomes 12.

5. Why are enums and typedef often used together?

Using typedef with an enum removes the need to repeatedly write the enum keyword, making declarations shorter and improving code readability.

typedef enum
{
    OFF,
    ON
} SwitchState;

SwitchState state = ON;
Prev: Storage ClassesBack to hub