Enums and Typedef in C
Enumeration (enum)
An enum is a user-defined data type consisting of named integer constants. It improves code readability.
Syntax:
enum enum_name { constant1, constant2, constant3, ... };
Example:
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN };
enum Day today = WED;
printf("Day number: %d\n", today); /* prints 2 (starts from 0) */
Custom values:
enum Status {
PENDING = 1,
ACTIVE = 2,
INACTIVE = 3
};
Enum in switch:
switch (today) {
case MON: printf("Monday"); break;
case FRI: printf("Friday"); break;
default: printf("Other day");
}
---
Enum vs #define
| Feature | enum | #define |
|---|---|---|
| Type safety | Yes (compiler checks) | No |
| Debuggable | Yes (names visible in debugger) | No |
| Scope | Follows C scope rules | Global |
| Arithmetic | Allowed | Allowed |
---
typedef
typedef creates an alias for an existing data type. It does not create a new type — just a new name.
Syntax:
typedef existing_type new_name;
Examples:
typedef int Integer;
typedef float Real;
typedef char* String;
Integer x = 10;
Real pi = 3.14;
typedef with struct:
/* Without typedef: */
struct Point { int x, y; };
struct Point p1;
/* With typedef: */
typedef struct {
int x, y;
} Point;
Point p1; /* no need to write 'struct' */
typedef with enum:
typedef enum { RED, GREEN, BLUE } Color;
Color c = GREEN;
typedef with pointer:
typedef int* IntPtr;
IntPtr p; /* same as: int *p; */
---
Combined Example
#include <stdio.h>
typedef enum { CIRCLE, RECTANGLE, TRIANGLE } ShapeType;
typedef struct {
ShapeType type;
float area;
} Shape;
int main() {
Shape s;
s.type = CIRCLE;
s.area = 3.14 * 5 * 5;
printf("Area = %.2f\n", s.area);
return 0;
}