ข้อผิดพลาดใน C/C++ แบ่งได้ 5 ประเภทหลัก ตามขั้นตอนของ Compilation และ Execution
1. Syntax Error (Compile-Time Error)
違反 กฎ Syntax ของภาษา Compiler จับได้ก่อน Compile เสร็จ
ตัวอย่าง: ขาด Semicolon
#include <stdio.h>
int main() {
printf("Hello World") // ขาด ;
}
ผลลัพธ์
Error: expected ';' before '}' token
2. Runtime Error
Compile ผ่าน แต่ Crash ระหว่างรัน
ตัวอย่าง: Divide by Zero
#include <stdio.h>
int main() {
int x = 52, y = 0;
printf("Div: %f", x / y); // Floating Point Exception
}
ผลลัพธ์
Program crashes during runtime (SIGFPE)
3. Linker Error
Compile แต่ละ File ผ่าน แต่ Link ไม่ได้ (Symbol ไม่เจอ)
ตัวอย่าง: main() เขียนผิดเป็น Main()
#include <stdio.h>
int Main() { // ต้องเป็น main ตัวเล็ก
return 0;
}
ผลลัพธ์
undefined reference to 'WinMain' (Windows) หรือ 'main' (Linux)
4. Logical Error
Compile/Run ผ่าน ผลลัพธ์ผิดเพราะ Logic ผิด
ตัวอย่าง: Semicolon หลัง For Loop
#include <stdio.h>
int main() {
for(int i = 0; i < 5; i++); { // ; ทำให้ Loop ว่าง
printf("Hello World\n"); // รันแค่ 1 ครั้ง
}
}
ผลลัพธ์
Hello World (พิมพ์แค่ 1 ครั้ง ไม่ใช่ 5 ครั้ง)
5. Semantic Error
Syntax ถูกต้อง แต่ไม่มีความหมาย (เช่น Grammar ผิด)
ตัวอย่าง: Expression ด้านซ้าย Assignment
#include <stdio.h>
int main() {
int x = 10, y = 20, z;
x + y = z; // Error: Lvalue required
}
ผลลัพธ์
Error: lvalue required as left operand of assignment
สรุปตารางเปรียบเทียบ
| Error Type | พบตอน | ตัวอย่าง | ความยากในการหา |
|---|---|---|---|
| Syntax | Compile Time | Missing ;, } , Typo Keyword | ง่าย (Compiler บอก) |
| Runtime | Execution | Div/0, Segfault, Null Ptr | ปานกลาง (ต้อง Reproduce) |
| Linker | Link Time | Missing Symbol, Wrong main() | ปานกลาง |
| Logical | Execution (Wrong Output) | Wrong Formula, Off-by-one | ยากที่สุด (โค้ดรันได้แต่ผิด) |
| Semantic | Compile Time | Lvalue Error, Type Mismatch | ง่าย (Compiler บอก) |
เครื่องมือช่วยหา Error
- Compiler Warnings:
-Wall -Wextra -pedantic - Static Analysis: Clang Static Analyzer, Cppcheck
- Debugger: GDB, LLDB
- Sanitizers: AddressSanitizer, UBSan (Undefined Behavior)
- Unit Testing: Google Test, Catch2