ในภาษา C ตัวแปร Global และ Static ทั้งคู่ต้องถูกเริ่มต้นค่าด้วยค่าคงที่ (constant values) เท่านั้น เนื่องจากค่าของตัวแปรเหล่านี้ต้องทราบก่อนเริ่มการทำงานของโปรแกรม หากไม่ได้กำหนดค่าคงที่ จะเกิดข้อผิดพลาดในการคอมไพล์
ตัวอย่างการเริ่มต้นค่าที่ถูกต้อง
#include <stdio.h>
int a = 5; // Global variable
static int b = 10; // Global static variable
int main() {
printf("The value of global variable a : %d", a);
printf("\nThe value of global static variable b : %d", b);
return 0;
}
ผลลัพธ์
The value of global variable a : 5
The value of global static variable b : 10
ตัวอย่างที่ทำให้เกิดข้อผิดพลาด
#include <stdio.h>
int func() {
return 25;
}
int main() {
static int a = func(); // Error: initializer element is not constant
printf("%d", a);
return 0;
}
โปรแกรมข้างต้นจะแสดงข้อผิดพลาด "initializer element is not constant" เพราะพยายามเริ่มต้นค่าตัวแปร static ด้วยค่าที่ได้จากการเรียกฟังก์ชัน (ซึ่งไม่ใช่ค่าคงที่)
ข้อสังเกตสำคัญ
- ตัวแปร Global และ Static ต้องใช้ค่าคงที่ในการเริ่มต้นเท่านั้น
- ไม่สามารถใช้ตัวแปร ฟังก์ชัน หรือนิพจน์ที่คำนวณได้ในขณะรันไทม์ (runtime) เป็นค่าเริ่มต้นได้
- ค่าคงที่รวมถึงตัวเลข ตัวอักษร สตริงลิทเทอร์ และนิพจน์ที่คำนวณได้ในขณะคอมไพล์ (compile-time constant expressions)