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

Undefined Behavior ใน C++ ที่โปรแกรมเมอร์ควรรู้

ใน C++ มี undefined behaviors (พฤติกรรมไม่ได้กำหนด) หลายกรณีที่โปรแกรมเมอร์ควรระวัง ไม่มีนิยามชัดเจนแต่เกิดจากการเขียนโค้ดบางรูปแบบ นี่คือตัวอย่างที่พบบ่อย:

1. หารศูนย์ (Divide by Zero)

int x = 10, y = 0; int z = x / y; // Runtime error

2. ใช้ตัวแปรที่ยังไม่ได้ initialize

bool x; if (x == true) ... // ผลลัพธ์ไม่แน่นอน ขึ้นกับคอมไพเลอร์

3. เข้าถึง null pointer

int *ptr = NULL; cout << *ptr; // Runtime error

4. เข้าถึงอาร์เรย์เกินขอบเขต (Out of Bounds)

int array[10]; for(int i=0; i<=10; i++) cout << array[i]; // อาจ error หรือค่ากะโหลกกะโถ

5. Signed Integer Overflow

int x = INT_MAX; cout << x + 1; // ลดรอบเป็นค่าต่ำสุด -2147483648

6. แก้ไข String Literal

char *str = "Hello World"; str[2] = 'x'; // Runtime error พยายามแก้ค่าคงที่

การเข้าใจจุดเหล่านี้ช่วยป้องกันบั๊กที่ค้นหายากและเพิ่มความน่าเชื่อถือของโค้ด