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

Storage Classes ในภาษา C: auto, extern, static, register


Storage Class คืออะไร?

Storage Class** กำหนด **Scope (ขอบเขต)**, **Lifetime (อายุการใช้งาน)**, **Default Value**, และ **Memory Location** ของตัวแปร/ฟังก์ชัน

4 Storage Classes ใน C

ClassKeywordScopeLifetimeDefault ValueMemory
AutomaticautoLocal (Block)จนจบ BlockGarbageStack
ExternalexternGlobal (File/Program)ตลอดโปรแกรม0Data Segment
StaticstaticLocal (Block) / Fileตลอดโปรแกรม0Data Segment
RegisterregisterLocal (Block)จนจบ BlockGarbageCPU Register (ถ้าได้)

1. Automatic (auto) - Local Variables

  • Default ของตัวแปรใน Block
  • สร้างเมื่อเข้า Block, ทำลายเมื่อออก Block
  • ค่าเริ่มต้น = Garbage

void demo() {
    auto int x = 10; // auto optional
    {
        auto int x = 20; // ตัวแปรใหม่ scope ภายใน
        printf("%d ", x); // 20
    }
    printf("%d ", x); // 10
}

2. External (extern) - Global Variables

  • ประกาศนอกฟังก์ชัน เข้าถึงได้ทุกไฟล์ (ถ้า declare extern)
  • ค่าเริ่มต้น = 0
  • ใช้ Share ตัวแปรระหว่างไฟล์ (.c หลายไฟล์)

// file1.c
int global_var = 10; // Definition

// file2.c
extern int global_var; // Declaration (ไม่จอง Memory)
// ใช้ global_var ได้

3. Static Variables

  • Static Local: ในฟังก์ชัน - คงค่าระหว่างการ Call ฟังก์ชัน
  • Static Global: นอกฟังก์ชัน - จำกัด Scope ให้อยู่ใน File นั้นๆ (Internal Linkage)
  • Initialize เพียงครั้งเดียว
  • ค่าเริ่มต้น = 0

void counter() {
    static int count = 0; // Init ครั้งเดียว
    count++;
    printf("%d ", count);
}

int main() {
    counter(); // 1
    counter(); // 2
    counter(); // 3
}

4. Register Variables

  • ขอให้ Compiler ใส่ใน CPU Register (เร็วที่สุด)
  • Compiler อาจไม่อนุมัติ (ขึ้นกับ Hardware/Optimization)
  • ไม่สามารถเอา Address ได้ (&var Error)
  • เหมาะกับ Loop Counter, Frequently Used Variables

void fast_loop() {
    register int i; // ขอ Register
    for (i = 0; i < 100000; i++) {
        // เร็วกว่าปกติเล็กน้อย (ถ้า Compiler อนุมัติ)
    }
}

ตัวอย่างเปรียบเทียบ Static vs Auto


#include 

void auto_func() {
    auto int a = 0;
    printf("Auto: %d\n", a++);
}

void static_func() {
    static int s = 0;
    printf("Static: %d\n", s++);
}

int main() {
    printf("Auto calls:\n");
    auto_func(); // 0
    auto_func(); // 0
    auto_func(); // 0
    
    printf("\nStatic calls:\n");
    static_func(); // 0
    static_func(); // 1
    static_func(); // 2
    return 0;
}

สรุปการเลือกใช้

  • auto - ตัวแปรทั่วไปในฟังก์ชัน (Default)
  • static - ต้องการจำค่าระหว่าง Call, หรือ ซ่อน Global ให้อยู่ File เดียว
  • extern - Share ตัวแปรข้ามไฟล์
  • register - Optimization เล็กน้อยสำหรับ Hot Variables (Modern Compiler ทำให้เองแล้ว)