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

คลาสการจัดเก็บ (Storage Classes) ในภาษา C

คลาสการจัดเก็บอธิบายลักษณะของตัวแปรและฟังก์ชัน เช่น ความมองเห็น (visibility) และขอบเขต (scope) มี 4 ประเภท: Automatic, External, Static, Register

auto

คลาสเริ่มต้นสำหรับตัวแปรโลคัล สร้างเมื่อเรียกฟังก์ชัน ทำลายเมื่อฟังก์ชันจบ ค่าเริ่มต้นเป็นค่าขยะ

  • ขอบเขต: ภายในบล็อกฟังก์ชัน
  • ค่าเริ่มต้น: Garbage value
  • อายุการใช้งาน: ผูกกับบล็อกที่ประกาศ

ตัวอย่าง

#include <stdio.h>
int main() {
    auto int a = 28;
    int b = 8;
    printf("The value of auto variable : %d\n", a);
    printf("The sum of auto variable & integer variable : %d", (a + b));
    return 0;
}

ผลลัพธ์

The value of auto variable : 28
The sum of auto variable & integer variable : 36

extern

ตัวแปรกลโบล ใช้อ้างอิงตัวแปรที่นิยามในไฟล์อื่น ค่าเริ่มต้นเป็น 0

  • ขอบเขต: ทั่วโปรแกรม
  • ค่าเริ่มต้น: 0
  • อายุการใช้งาน: จนจบโปรแกรม

ตัวอย่าง

#include <stdio.h>
extern int x = 32;
int b = 8;
int main() {
    auto int a = 28;
    extern int b;
    printf("The value of auto variable : %d\n", a);
    printf("The value of extern variables x and b : %d,%d\n", x, b);
    x = 15;
    printf("The value of modified extern variable x : %d\n", x);
    return 0;
}

ผลลัพธ์

The value of auto variable : 28
The value of extern variables x and b : 32,8
The value of modified extern variable x : 15

static

เริ่มต้นค่าเพียงครั้งเดียว คงค่าระหว่างการเรียกฟังก์ชัน ประกาศภายในหรือนอกฟังก์ชันได้

  • ขอบเขต: ภายในบล็อก
  • ค่าเริ่มต้น: 0
  • อายุการใช้งาน: จนจบโปรแกรม

ตัวอย่าง

#include <stdio.h>
int main() {
    auto int a = -28;
    static int b = 8;
    printf("The value of auto variable : %d\n", a);
    printf("The value of static variable b : %d\n", b);
    if (a != 0)
        printf("The sum of static variable and auto variable : %d\n", (b + a));
    return 0;
}

ผลลัพธ์

The value of auto variable : -28
The value of static variable b : 8
The sum of static variable and auto variable : -20

register

ขอให้คอมไพเลอร์เก็บในรีจิสเตอร์ CPU เข้าถึงเร็ว ไม่สามารถ取得ที่อยู่ได้

  • ขอบเขต: ภายในฟังก์ชัน
  • ค่าเริ่มต้น: Garbage value
  • อายุการใช้งาน: จนจบบล็อกที่ประกาศ

ตัวอย่าง

#include <stdio.h>
int main() {
    register char x = 'S';
    register int a = 10;
    auto int b = 8;
    printf("The value of register variable b : %c\n", x);
    printf("The sum of auto and register variable : %d", (a + b));
    return 0;
}

ผลลัพธ์

The value of register variable b : S
The sum of auto and register variable : 18