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

Static Storage Class ในภาษา C

Storage Classes ใน C (4 ชนิด)

  • auto
  • extern
  • static
  • register

Static Variables

คีย์เวิร์ด: static

คุณสมบัติ

  • Lifetime: ตลอดการรันโปรแกรม (program duration) ไม่ถูก destroy เมื่อออกจาก block
  • Scope: ขึ้นอยู่กับตำแหน่งการประกาศ (block scope หรือ file scope)
  • Initialization: ทำเพียงครั้งเดียว (ครั้งแรกที่ผ่าน)
  • Default value: 0 (zero-initialized)

ตัวอย่างที่ 1: Static Local Variable ในฟังก์ชัน

#include <stdio.h>
void inc() {
    static int i = 1; // initialize ครั้งเดียว
    printf("%d ", i);
    i++;
}
int main() {
    inc(); // 1
    inc(); // 2
    inc(); // 3
    return 0;
}

ผลลัพธ์

1 2 3

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

#include <stdio.h>
void inc_static() {
    static int i = 1;
    printf("%d ", i);
    i++;
}
void inc_auto() {
    auto int i = 1; // auto = local variable ปกติ
    printf("%d ", i);
    i++;
}
int main() {
    printf("Static: ");
    inc_static(); inc_static(); inc_static(); // 1 2 3
    printf("\\nAuto: ");
    inc_auto(); inc_auto(); inc_auto(); // 1 1 1
    return 0;
}

ผลลัพธ์

Static: 1 2 3
Auto: 1 1 1

ตัวอย่างที่ 3: Static Variable นับจำนวนครั้งที่เรียกฟังก์ชัน

#include <stdio.h>
void function();
int main() {
    function(); // 1
    function(); // 2
    return 0;
}
void function() {
    static int value = 1;
    printf("\\nvalue = %d", value);
    value++;
}

ผลลัพธ์

value = 1
value = 2

Static Variable ที่ File Scope (Global Static)

// file1.c
static int global_counter = 0; // ใช้ได้เฉพาะใน file1.c เท่านั้น
void increment() { global_counter++; }

// file2.c
// ไม่สามารถเข้าถึง global_counter ได้ (internal linkage)

สรุป Static Storage Class

บริบทScopeLifetimeLinkage
static ในฟังก์ชันBlock (ฟังก์ชันนั้นๆ)โปรแกรมทั้งหมดNo linkage
static ที่ file scopeFile (translation unit)โปรแกรมทั้งหมดInternal linkage

การประยุกต์ใช้

  • นับจำนวนครั้งที่ฟังก์ชันถูกเรียก
  • เก็บสถานะ (state) ระหว่างการเรียกฟังก์ชัน
  • Singleton pattern
  • ซ่อน global variable ไม่ให้ link ไฟล์อื่นเข้าถึง (file scope static)