Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Enumerated Data Type (Enum) ในภาษา C

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...)ต้องกำหนดเอง
Sizesizeof(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 ขนาดพอดี