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

การใช้ typedef กับ Structure ในภาษา C

typedef** เป็นคีย์เวิร์ดใน C ที่ใช้สร้าง ชื่อใหม่ (Alias) ให้กับชนิดข้อมูลที่มีอยู่แล้ว ไม่ได้สร้างชนิดข้อมูลใหม่ แต่ทำให้โค้ดอ่านง่ายขึ้น

ไวยากรณ์

typedef existing_type new_name;

ตัวอย่างพื้นฐาน

typedef int hours;  // hours คือชื่อใหม่ของ int

hours h;  // เทียบเท่า int h;
h = 2;
printf("Minutes: %d", h * 60);   // 120
printf("Seconds: %d", h * 3600); // 7200

typedef กับ Structure

ปกติการประกาศ Struct ต้องใช้คีย์เวิร์ด struct ทุกครั้ง:

struct employee {
    int eno;
    char ename[30];
    float sal;
};

struct employee e1, e2;  // ต้องเขียน struct ทุกครั้ง

ใช้ typedef** ลดความยุ่งยาก:

typedef struct employee {
    int eno;
    char ename[30];
    float sal;
} emp;  // emp คือชื่อใหม่ของ struct employee

emp e1, e2;  // ใช้ emp ได้เลย ไม่ต้องเขียน struct

ตัวอย่างโปรแกรมครบถ้วน

#include <stdio.h>

typedef struct employee {
    int eno;
    char ename[30];
    float sal;
} emp;

int main() {
    emp e = {10, "ramu", 5000.0};
    
    printf("Number = %d\n", e.eno);
    printf("Name = %s\n", e.ename);
    printf("Salary = %.2f\n", e.sal);
    
    // สร้างอาร์เรย์ของ emp ได้ง่าย
    emp staff[3] = {
        {1, "Alice", 25000},
        {2, "Bob", 30000},
        {3, "Carol", 28000}
    };
    
    for(int i = 0; i < 3; i++)
        printf("%d: %s - %.2f\n", staff[i].eno, staff[i].ename, staff[i].sal);
    
    return 0;
}

ผลลัพธ์

Number = 10
Name = ramu
Salary = 5000.00
1: Alice - 25000.00
2: Bob - 30000.00
3: Carol - 28000.00

ข้อดีของ typedef กับ Struct

  • โค้ดสั้น กระชับ อ่านง่าย
  • ลดโอกาสผิดพลาดจากการพิมพ์ struct ซ้ำ
  • สร้างอาร์เรย์/พอยน์เตอร์ของ Struct ได้สะดวก
  • เป็นมาตรฐานในโปรเจกต์ใหญ่ (เช่น Linux Kernel ใช้ typedef อย่างแพร่หลาย)

แนวทางปฏิบัติที่ดี (Best Practice)

// ชื่อ typedef ใช้ _t ต่อท้าย (POSIX standard)
typedef struct node_s {
    int data;
    struct node_s *next;
} node_t;