ตัวแปร Global และ Static ถูกเริ่มต้นค่าเริ่มต้น (default initialization) เป็นศูนย์ (0) อัตโนมัติ ตามมาตรฐานของ C และ C++ เนื่องจาก:
- มาตรฐานภาษา (Language Standard) - กำหนดให้ทำเช่นนี้เพื่อความปลอดภัยและพฤติกรรมที่คาดเดาได้
- ประสิทธิภาพในการคอมไพล์ (Compile-time efficiency) - การตั้งค่าเป็นศูนย์เป็นค่าใช้จ่ายน้อยมาก (zeroing memory)
- การจัดสรรหน่วยความจำ (Memory allocation) - ตัวแปรเหล่านี้ถูกจัดสรรใน
.bsssection (Block Started by Symbol) ซึ่ง loader จะทำการ zero-fill อัตโนมัติเมื่อโหลดโปรแกรม
ตัวอย่าง
#include <stdio.h>
int a; // global variable
static int b; // global static variable
int main() {
int x; // local variable (auto)
static int y; // local static variable
int z = 28; // local variable with initialization
printf("The default value of global variable a : %d\n", a);
printf("The default value of global static variable b : %d\n", b);
printf("The default value of local variable x : %d\n", x);
printf("The default value of local static variable y : %d\n", y);
printf("The value of local variable z : %d\n", z);
return 0;
}
ผลลัพธ์
The default value of global variable a : 0
The default value of global static variable b : 0
The default value of local variable x : 0
The default value of local static variable y : 0
The value of local variable z : 28
คำอธิบาย
| ตัวแปร | ประเภท | ค่าเริ่มต้น | เหตุผล |
|---|---|---|---|
| a | Global | 0 | Global variables ถูก zero-initialize อัตโนมัติ |
| b | Global static | 0 | Static variables ถูก zero-initialize อัตโนมัติ |
| x | Local (auto) | 0* | **ไม่ได้รับการ initialize อัตโนมัติ** - ค่านี้เป็น garbage value (ในตัวอย่างแสดง 0 แต่อาจเป็นค่าใดก็ได้) |
| y | Local static | 0 | Static variables ถูก zero-initialize อัตโนมัติ |
| z | Local (initialized) | 28 | กำหนดค่าเริ่มต้นชัดเจน |
หมายเหตุสำคัญ: ตัวแปร Local (automatic) ที่ ไม่ได้กำหนดค่าเริ่มต้น จะมีค่า Indeterminate (garbage value) ไม่ใช่ 0 เสมอไป ตัวอย่างข้างต้นแสดง 0 เพราะ compiler/optimizer แต่ไม่รับประกัน
Memory Sections
.data section -> initialized global/static variables (non-zero)
.bss section -> uninitialized global/static variables (zero-filled by loader)
.stack -> local variables (no automatic initialization)
.heap -> dynamic allocation (malloc/new - no automatic initialization)
Best Practice
- เริ่มต้นค่าตัวแปร Local เสมอ - อย่าพึ่งพา default initialization
- ใช้
staticหรือglobalเมื่อต้องการค่าเริ่มต้นเป็น 0 อัตโนมัติ - ใน C++ ใช้ constructor หรือ brace initialization
int x{}เพื่อ zero-initialize