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 Class | Storage Area | Default Initial Value | Lifetime | Scope | Keyword |
|---|---|---|---|---|---|
| Automatic | Memory | Garbage | จนกว่าจะออกจากบล็อก | Local | auto |
| Register | CPU Register | Garbage | จนกว่าจะออกจากบล็อก | Local | register |
| Static | Memory | Zero | คงค่าระหว่างเรียกฟังก์ชัน | Local | static |
| External | Memory | Garbage | ตลอดการรันโปรแกรม | Global | extern |
ตัวอย่าง 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