Enum and Typedef in C Programming
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
| Feature | Use when |
|---|---|
enum | Related named constants (days, states, errors) |
typedef | Simplifying 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
typedefwithstructto avoid repeatingstructkeyword.
Common Mistakes
- Assuming enum size — in C it is implementation-defined (often
int). - typedef confusion —
typedefdoes not create a new distinct type for type checking in C (unlike C++).
Related Pages
Continue learning with these related tutorials and programs:
- C Tutorials — Browse all C Tutorials.
- C Array — Concept hub — start with arrays before pointers.
- C Strings in C Programming — More in c concepts.
- C Functions — More in c concepts.