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

ค่าของ Primitive Data Types ที่ไม่ได้ Initialize ใน C/C++


Uninitialized Variables คืออะไร?

ตัวแปรที่ประกาศแต่ **ไม่ได้กำหนดค่าเริ่มต้น** จะมีค่า **Indeterminate (Garbage Value)**

พฤติกรรมใน C/C++

  • Local Variables (Auto/Register) → Garbage Value (Indeterminate)
  • Static/Global Variables → Zero-Initialized อัตโนมัติ
  • Heap (malloc) → Garbage Value
  • Heap (calloc) → Zero-Initialized

ตัวอย่างโปรแกรม (C++)


#include 
using namespace std;

int main() {
    char char_var;
    float float_var;
    int int_var;
    double double_var;
    long long_var;
    
    cout << "char: " << (int)char_var << endl;
    cout << "float: " << float_var << endl;
    cout << "int: " << int_var << endl;
    cout << "double: " << double_var << endl;
    cout << "long: " << long_var << endl;
    return 0;
}

ผลลัพธ์จาก Compiler ต่างๆ (Unpredictable!)

ทำไม Compiler ไม่ Initialize ให้อัตโนมัติ?

  1. Performance: การ Initialize ทุกตัวแปรบน Stack ใช้ CPU Cycles → ช้าลง
  2. C Philosophy: "Trust the Programmer" - ให้โปรแกรมเมอร์จัดการเอง
  3. Hardware: Register/Stack Memory ไม่มีค่า Default จาก Hardware

Best Practice: Initialize เสมอ!


// ✅ Good
int x = 0;
float f = 0.0f;
char c = '\0';
int arr[10] = {0};
int *p = malloc(n * sizeof(int));
if (p) memset(p, 0, n * sizeof(int)); // หรือ calloc

// ❌ Bad
int x;
float f;
char c;
int arr[10];
int *p = malloc(n * sizeof(int));

Tools ตรวจจับ Uninitialized Variables

  • Compiler Warnings: -Wall -Wuninitialized (GCC/Clang)
  • Static Analysis: cppcheck, clang-tidy, Coverity
  • Runtime: Valgrind --track-origins=yes, AddressSanitizer (-fsanitize=memory)
  • C++: ใช้ std::optional, std::variant แทน Raw Variables

Special Case: C++ Class Members


struct Foo {
    int x; // Uninitialized ถ้าไม่มี Constructor
    int y = 0; // C++11 In-class Initializer ✅
};

Foo f1; // f1.x = Garbage, f1.y = 0
Foo f2{}; // Value Initialization: f2.x = 0, f2.y = 0 ✅
กฎข้างมือ: Initialize ทุกตัวแปรทันทีที่ประกาศ ไม่มีข้อยกเว้น!
Compiler/Environmentcharfloatintdoublelong
Cpp.sh (Online)00000
OnlineGDB-5.88e-3906.95e-3100
Local (GCC/Linux)-9.73e-3943097441.15e-306-53505136
MSVC (Debug)--0xCCCCCCCC--