ตัวแปร Static ใน C จะถูกเริ่มต้นค่าเป็น ศูนย์ (0) อัตโนมัติ หากไม่ได้ระบุค่าเริ่มต้นชัดเจน นี่เป็นพฤติกรรมที่รับประกันโดยมาตรฐาน C
คุณสมบัติ Static Variables
- Initialized Once: เริ่มต้นค่าเพียงครั้งเดียว (Compile-time/Load-time)
- Default Zero: ค่าเริ่มต้นคือ 0 สำหรับทุกชนิดข้อมูล
- Lifetime: ตลอดการทำงานของโปรแกรม
- Storage: เก็บใน BSS Segment (Uninitialized Data Segment)
ไวยากรณ์
static datatype variable_name; // ค่าเริ่มต้น = 0
static datatype variable_name = value; // ค่าเริ่มต้น = value
ตัวอย่าง: Static vs Non-Static Local Variables
#include <stdio.h>
int main() {
static int a; // Static Local - Default 0
int b; // Automatic Local - Garbage Value
printf("Default value of static variable : %d\n", a);
printf("Default value of non-static variable : %d\n", b);
return 0;
}
ผลลัพธ์
Default value of static variable : 0
Default value of non-static variable : 0
หมายเหตุ: ตัวแปร b (Automatic) แสดง 0 ในตัวอย่างนี้เพราะ Compiler/Stack State แต่ ไม่รับประกัน ค่าจริงคือ Indeterminate (Garbage)
ค่าเริ่มต้นตามชนิดข้อมูล
| ชนิดข้อมูล | ค่าเริ่มต้นของ Static | ตัวแทนในหน่วยความจำ |
|---|---|---|
| Integer (int, short, long) | 0 | All bits zero |
| Float/Double | 0.0 | All bits zero (IEEE 754) |
| Pointer | NULL | All bits zero (Null Pointer) |
| Struct/Union | Zero-initialized | ทุก Member เป็น 0/NULL |
| Array | Zero-initialized | ทุก Element เป็น 0 |
ตัวอย่างชนิดข้อมูลต่างๆ
#include <stdio.h>
static int i;
static float f;
static double d;
static char *ptr;
static int arr[3];
int main() {
printf("int: %d\n", i); // 0
printf("float: %f\n", f); // 0.000000
printf("double: %f\n", d); // 0.000000
printf("pointer: %p\n", (void*)ptr); // (nil) / 0x0
printf("arr[0]: %d\n", arr[0]); // 0
return 0;
}
Static vs Global vs Automatic
| ประเภท | ค่าเริ่มต้น | Storage | Lifetime |
|---|---|---|---|
| Global (Non-static) | 0 (Implicit) | .data/.bss | Program |
| Global Static | 0 (Implicit) | .data/.bss | Program |
| Local Static | 0 (Implicit) | .data/.bss | Program |
| Local Automatic | Garbage (Indeterminate) | Stack | Function Call |
ข้อสังเกตสำคัญ
- Global Variables และ Static Variables (ทั้ง Local และ Global) มีพฤติกรรมเริ่มต้นค่าเหมือนกัน: Zero Initialization
- Local Automatic Variables ไม่มี** ค่าเริ่มต้นอัตโนมัติ
- ใน C++: Static Local Variable Initialization เป็น Thread-safe (C++11+) แต่ C ไม่รับประกัน
- Zero Initialization เกิดขึ้นก่อน Constant Initialization (ถ้ามี)
Best Practice
// แม้จะ Default เป็น 0 แต่อย่าพึ่งพา - ระบุชัดเจนเพื่อความอ่านง่าย
static int counter = 0; // ดี: ชัดเจน
static int counter; // ทำงานได้แต่อ่านยาก
// สำหรับ Pointer
static char *str = NULL; // ดี: ชัดเจนว่าเป็น NULL Pointer