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

อายุการมีอยู่ของตัวแปร (Lifetime) ในภาษา C

Storage class ระบุ scope, lifetime และ binding ของตัวแปร

Storage class บอก: ที่เก็บ, ค่าเริ่มต้น, scope, lifetime

Lifetime

Lifetime คือระยะเวลาที่คอมพิวเตอร์จัดสรรหน่วยความจำให้ตัวแปร (ระหว่าง allocate และ deallocate)

ใน C ตัวแปรมี lifetime 3 แบบ:

  • Automatic - สร้างทุกครั้งที่เจอ declaration ทำลายเมื่อออกจากบล็อก
  • Static - สร้างครั้งแรกที่เจอ declaration ทำลายเมื่อโปรแกรมจบ
  • Dynamic - จัดสรร/ปล่อยผ่านฟังก์ชันจัดการหน่วยความจำ

Storage Classes (4 แบบ)

Storage ClassStorage AreaDefault Initial ValueLifetimeScopeKeyword
AutomaticMemoryGarbageจนกว่าจะออกจากบล็อกLocalauto
RegisterCPU RegisterGarbageจนกว่าจะออกจากบล็อกLocalregister
StaticMemoryZeroคงค่าระหว่างเรียกฟังก์ชันLocalstatic
ExternalMemoryGarbageตลอดการรันโปรแกรมGlobalextern

ตัวอย่าง Automatic

#include <stdio.h>
int main() {
    auto int i = 1;
    {
        auto int i = 2;
        {
            auto int i = 3;
            printf("%d", i);
        }
        printf("%d", i);
    }
    printf("%d", i);
    return 0;
}

ผลลัพธ์

3 2 1

ตัวอย่าง External

#include <stdio.h>
extern int i = 1; /* i นี้เข้าถึงได้ทั่วโปรแกรม */
int main() {
    int i = 3; /* i นี้เฉพาะใน main */
    printf("%d", i);
    fun();
}
void fun() {
    printf("%d", i);
}

ผลลัพธ์

3 1