Enum (Enumerated Type)** ให้โปรแกรมเมอร์สร้างชนิดข้อมูลแบบกำหนดค่าคงที่ (Named Constants) เอง ทำให้โค้ดอ่านง่ายและปลอดภัยกว่า #define
ไวยากรณ์
enum tagname {
identifier1,
identifier2,
...
identifierN
};
ค่า Default
- ตัวแรก = 0
- ตัวถัดไป = ค่าก่อนหน้า + 1
- เป็น Unsigned Integer
ตัวอย่างพื้นฐาน: วันในสัปดาห์
#include <stdio.h>
enum week {
mon, tue, wed, thu, fri, sat, sun
};
int main() {
printf("Monday = %d\n", mon); // 0
printf("Thursday = %d\n", thu); // 3
printf("Sunday = %d\n", sun); // 6
enum week today = wed;
printf("Today = %d\n", today); // 2
return 0;
}
ผลลัพธ์
Monday = 0 Thursday = 3 Sunday = 6 Today = 2
กำหนดค่าเอง (Explicit Values)
enum week {
mon = 1, // เริ่มที่ 1
tue, // 2
wed, // 3
thu, // 4
fri, // 5
sat, // 6
sun // 7
};
enum status {
OK = 0,
ERROR = -1,
PENDING = 10,
CANCELLED = 20
};
ตัวอย่าง: ใช้ Enum ใน Switch Case
#include <stdio.h>
typedef enum {
STATE_IDLE,
STATE_RUNNING,
STATE_PAUSED,
STATE_STOPPED
} State;
void handleState(State s) {
switch(s) {
case STATE_IDLE: printf("System Idle\n"); break;
case STATE_RUNNING: printf("System Running\n"); break;
case STATE_PAUSED: printf("System Paused\n"); break;
case STATE_STOPPED: printf("System Stopped\n"); break;
default: printf("Unknown State\n");
}
}
int main() {
State current = STATE_RUNNING;
handleState(current);
handleState(STATE_PAUSED);
return 0;
}
ผลลัพธ์
System Running System Paused
Enum vs #define
| ลักษณะ | enum | #define |
|---|---|---|
| Type Safety | มี (Compiler ตรวจสอบ) | ไม่มี (Text Substitution) |
| Debugging | เห็นชื่อใน Debugger | เห็นแค่ตัวเลข |
| Scope | มี Scope (Block/File) | Global (Preprocessor) |
| Auto Numbering | ได้ (0, 1, 2...) | ต้องกำหนดเอง |
| Size | sizeof(enum) = sizeof(int) ปกติ | ไม่มีขนาด |
Best Practices
- ใช้ typedef enum เพื่อสร้าง Type Name
- Prefix Enum Values:
COLOR_REDไม่ใช่แค่RED - ใส่
_COUNTหรือ_MAXท้ายสุดสำหรับนับจำนวน - ใช้
enum classใน C++ (Scoped Enum) แต่ C ไม่มี
typedef enum {
COLOR_RED = 0,
COLOR_GREEN,
COLOR_BLUE,
COLOR_COUNT // = 3 ใช้สำหรับ Array Size
} Color;
Color palette[COLOR_COUNT]; // Array ขนาดพอดี