Static Variables เริ่มต้นค่าเพียงครั้งเดียว คงค่าระหว่างการเรียกฟังก์ชัน มีอายุการใช้งานตลอดโปรแกรม ค่าเริ่มต้นเป็น 0
รูปแบบ
static datatype variable_name = value;
ตัวอย่างโค้ด
#include <stdio.h>
int main() {
auto int a = -28; // Auto (Local) Variable
static int b = 8; // Static Variable
printf("The value of auto variable : %d\n", a);
printf("The value of static variable b : %d\n", b);
if (a != 0)
printf("The sum of static variable and auto variable : %d\n", (b + a));
return 0;
}
ผลลัพธ์
The value of auto variable : -28
The value of static variable b : 8
The sum of static variable and auto variable : -20
ประเภท Static Variables
| ประเภท | Scope | Lifetime | Initialization |
|---|---|---|---|
| Static Local (ในฟังก์ชัน) | Local to Function | Program Duration | Once (First Call) |
| Static Global (File Scope) | File (Internal Linkage) | Program Duration | At Startup |
| Static Member (ในคลาส C++) | Class Scope | Program Duration | Definition Required |
ตัวอย่าง Static Local (นับครั้งที่เรียก)
void counter() {
static int count = 0;
count++;
printf("Called %d times\n", count);
}