Skip to main content

Enum and Typedef in C Programming

2 min read
Share:
On this page (10sections)

Introduction

enum creates a set of named integer constants. typedef gives a new name to an existing type, improving readability and portability.

enum — Named Constants

#include <stdio.h>

enum Day { SUN, MON, TUE, WED, THU, FRI, SAT };

int main(void) {
    enum Day today = WED;
    printf("Day number: %d\n", today);
    return 0;
}

Sample Output

Day number: 3

Enum values start at 0 by default and increment by 1. You can assign explicit values:

enum Status { OK = 1, ERROR = -1, PENDING = 0 };

typedef — Type Aliases

typedef unsigned int uint;
typedef struct {
    int x;
    int y;
} Point;

int main(void) {
    uint count = 100;
    Point p = { 10, 20 };
    printf("count=%u, point=(%d,%d)\n", count, p.x, p.y);
    return 0;
}

Sample Output

count=100, point=(10,20)

Combining enum and typedef (C style)

typedef enum { RED, GREEN, BLUE } Color;
Color c = GREEN;

When to Use

FeatureUse when
enumRelated named constants (days, states, errors)
typedefSimplifying complex types (uint, Point, function pointers)

Best Practices

  • Use descriptive enum names in ALL_CAPS by convention.
  • Prefer scoped enums in C++ projects; in C, prefix enum values (STATUS_OK).
  • Use typedef with struct to avoid repeating struct keyword.

Common Mistakes

  • Assuming enum size — in C it is implementation-defined (often int).
  • typedef confusion — typedef does not create a new distinct type for type checking in C (unlike C++).

Continue learning with these related tutorials and programs:

Related Tutorials

Search tutorials