Storage Classes ใน C (4 ชนิด)
- auto
- extern
- static
- register
Automatic Variables (Local Variables)
คีย์เวิร์ด: auto (เป็น default สำหรับ local variables ไม่ต้องเขียนก็ได้)
คุณสมบัติ
- Scope: ใช้ได้เฉพาะใน block ที่ประกาศ (block scope)
- Lifetime: สร้างเมื่อเข้าบล็อก ทำลายเมื่อออกจากบล็อก
- Default value: Garbage value (ไม่ initialize อัตโนมัติ)
- Storage: Stack memory
อัลกอริทึมแสดง Scope แบบ Nested
START
Step 1: auto int i = 1 (outer block)
I. auto int i = 2 (middle block)
I. auto int i = 3 (inner block) -> print 3
II. print i -> 2 (middle block)
Step 2: print i -> 1 (outer block)
STOPตัวอย่างที่ 1: Nested Blocks กับ Auto Variables
#include <stdio.h>
int main() {
auto int i = 1; // outer
{
auto int i = 2; // middle (shadow outer)
{
auto int i = 3; // inner (shadow middle)
printf("%d ", i); // 3
}
printf("%d ", i); // 2
}
printf("%d ", i); // 1
return 0;
}ผลลัพธ์
3 2 1
ตัวอย่างที่ 2: Auto Variable ในฟังก์ชัน
#include <stdio.h>
int mul(int num1, int num2) {
auto int result; // local variable (auto เป็น default)
result = num1 * num2;
return result;
}
int main() {
int p, q, r;
printf("ป้อน p, q: ");
scanf("%d%d", &p, &q);
r = mul(p, q);
printf("ผลคูณ = %d\\n", r);
return 0;
}ผลลัพธ์ตัวอย่าง
ป้อน p, q: 3 5 ผลคูณ = 15
Auto vs Static ในฟังก์ชัน
| คุณสมบัติ | auto (local) | static local |
|---|---|---|
| Lifetime | เฉพาะระหว่างการเรียกฟังก์ชัน | ตลอดโปรแกรม |
| ค่าเริ่มต้น | Garbage | 0 |
| การ Initialize | ทุกครั้งที่เรียก | ครั้งแรกเท่านั้น |
| คงค่าระหว่างการเรียก | ไม่ | ใช่ |
| Memory | Stack | Data segment (BSS/Data) |
หมายเหตุ
- ใน C สมัยใหม่ ไม่ต้องเขียน
autoก็ได้ เพราะเป็น default - C++11 ใช้
autoสำหรับ type deduction (ความหมายต่างกัน) - register เป็น hint ให้ compiler ใส่ใน register (modern compilers ignore)