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/Environment | char | float | int | double | long |
| Cpp.sh (Online) | 0 | 0 | 0 | 0 | 0 |
| OnlineGDB | - | 5.88e-39 | 0 | 6.95e-310 | 0 |
| Local (GCC/Linux) | - | 9.73e-39 | 4309744 | 1.15e-306 | -53505136 |
| MSVC (Debug) | - | - | 0xCCCCCCCC | - | - |
ทำไม Compiler ไม่ Initialize ให้อัตโนมัติ?
- Performance: การ Initialize ทุกตัวแปรบน Stack ใช้ CPU Cycles → ช้าลง
- C Philosophy: "Trust the Programmer" - ให้โปรแกรมเมอร์จัดการเอง
- 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 ทุกตัวแปรทันทีที่ประกาศ ไม่มีข้อยกเว้น!