Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ทำไมตัวแปร Global และ Static ถึงถูกเริ่มต้นค่าเริ่มต้นใน C/C++

ตัวแปร Global และ Static ถูกเริ่มต้นค่าเริ่มต้น (default initialization) เป็นศูนย์ (0) อัตโนมัติ ตามมาตรฐานของ C และ C++ เนื่องจาก:

  1. มาตรฐานภาษา (Language Standard) - กำหนดให้ทำเช่นนี้เพื่อความปลอดภัยและพฤติกรรมที่คาดเดาได้
  2. ประสิทธิภาพในการคอมไพล์ (Compile-time efficiency) - การตั้งค่าเป็นศูนย์เป็นค่าใช้จ่ายน้อยมาก (zeroing memory)
  3. การจัดสรรหน่วยความจำ (Memory allocation) - ตัวแปรเหล่านี้ถูกจัดสรรใน .bss section (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

คำอธิบาย

ตัวแปรประเภทค่าเริ่มต้นเหตุผล
aGlobal0Global variables ถูก zero-initialize อัตโนมัติ
bGlobal static0Static variables ถูก zero-initialize อัตโนมัติ
xLocal (auto)0***ไม่ได้รับการ initialize อัตโนมัติ** - ค่านี้เป็น garbage value (ในตัวอย่างแสดง 0 แต่อาจเป็นค่าใดก็ได้)
yLocal static0Static variables ถูก zero-initialize อัตโนมัติ
zLocal (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