Enum and Typedef in C Programming
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: 3Enum 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
Common Mistakes
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.
Frequently Asked Questions
What does this C program do?
It is a C example program that demonstrates Enum and Typedef, including the complete source code and the expected sample output.
How do I compile and run this C program?
Save the code in a `.c` file, compile it with `gcc filename.c -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses user-defined functions, illustrating a common pattern in C programming.