ตัวแปร Static (static variables) เป็นตัวแปรที่คงอยู่ในหน่วยความจำตลอดการทำงานของโปรแกรม (lifetime = entire program run) ซึ่งต่างจากตัวแปรอัตโนมัติ (automatic variables) ที่มีอยู่เฉพาะขณะฟังก์ชันทำงานและถูกทำลายเมื่อฟังก์ชันจบ
ตำแหน่งในหน่วยความจำ
ตัวแปร Static ถูกเก็บใน Data Segment (Data Section) ของหน่วยความจำ ซึ่งเป็นส่วนหนึ่งของ virtual address space ของโปรแกรม
แบ่งเป็น 2 ส่วนย่อย:
- Initialized Data Segment (Data Segment จริงๆ) - เก็บ static variables ที่มีการกำหนดค่าเริ่มต้นชัดเจน (explicit initialization)
- Uninitialized Data Segment (BSS Segment - Block Started by Symbol) - เก็บ static variables ที่ ไม่ได้กำหนดค่าเริ่มต้น หรือกำหนดเป็นศูนย์ (zero-initialized)
ตัวอย่าง
static int x = 5; // เก็บใน Initialized Data Segment
static int y; // เก็บใน BSS Segment (ค่าเริ่มต้น = 0)
ตัวอย่างโปรแกรมแสดงพฤติกรรม Static Variable
#include <stdio.h>
int func() {
static int i = 4; // initialized data segment
i++;
return i;
}
int main() {
printf("%d\n", func()); // 5
printf("%d\n", func()); // 6
printf("%d\n", func()); // 7
printf("%d\n", func()); // 8
printf("%d\n", func()); // 9
printf("%d\n", func()); // 10
return 0;
}
ผลลัพธ์
5
6
7
8
9
10
คำอธิบาย
- ใน
func():static int i = 4ถูกสร้างและเริ่มต้นครั้งเดียว (first call only) เก็บใน initialized data segment i++เพิ่มค่าและคืนค่า- ใน
main(): เรียกfunc()6 ครั้ง - เพราะ
iเป็น static จึงคงค่าไว้ระหว่างการเรียก ไม่ถูกสร้างใหม่ทุกครั้ง
สรุป Memory Layout
+------------------+ High Address
| Stack | (local variables, function calls)
| ... |
| Heap | (malloc, new)
| ... |
| BSS Segment | (uninitialized static/global)
| Data Segment | (initialized static/global)
| Text/Code Segment| (program code)
+------------------+ Low Address
ข้อดีของการใช้ Static Variables
- รักษาค่าไว้ระหว่างการเรียกฟังก์ชัน (stateful functions)
- ไม่ใช้ stack memory
- Thread-safe สำหรับการเริ่มต้น (C++11 onwards)