Type Conversion (การแปลงชนิดข้อมูล)
การแปลงค่าจากชนิดข้อมูลหนึ่งไปอีกชนิดหนึ่ง แบ่ง 2 แบบ:
1. Implicit Type Conversion (อัตโนมัติ)
- คอมไพเลอร์ทำเอง เมื่อ Operand ชนิดต่างกัน
- แปลง **Smaller Type → Larger Type** (Type Promotion)
- ป้องกัน Data Loss
Hierarchy (ลำดับความกว้าง)
long double (กว้างสุด)
↑
double
↑
float
↑
unsigned long long
↑
long long / unsigned long
↑
long / unsigned int
↑
int (Base Rank)
↑
char / short / bool (Promote เป็น int)
ตัวอย่าง Implicit
int i = 10;
float f = 3.14;
double d = i + f; // i → float → double, ผลลัพธ์ double
โค้ดตัวอย่าง
#include
int main() {
int i = 40;
float a;
a = i; // Implicit: int → float
printf("Implicit value: %f\n", a); // 40.000000
return 0;
}
2. Explicit Type Conversion (Type Casting - แบบระบุชัด)
- โปรแกรมเมอร์ระบุชนิดปลายทางด้วย
(type) - อาจเกิด **Data Loss** (Truncation, Overflow)
- ใช้เมื่อแน่ใจว่าค่าพอดี หรือต้องการ Truncate
Syntax
(target_type) expression
ตัวอย่าง Explicit
float f = 3.14;
int i = (int)f; // i = 3 (Truncate ทศนิยม)
double d = 1e20;
int x = (int)d; // Overflow! ผลลัพธ์ไม่แน่นอน
โค้ดตัวอย่าง
#include
int main() {
int i = 40;
short s;
s = (short)i; // Explicit: int → short
printf("Explicit value: %d\n", s); // 40
// Data Loss Example
int big = 100000;
short small = (short)big; // Overflow!
printf("Big: %d, Small: %d\n", big, small); // ผลลัพธ์แปลก
return 0;
}
ตัวอย่างเปรียบเทียบ: Implicit vs Explicit ใน Loop
// Implicit (ใน %c format specifier)
for (int x = 97; x <= 122; x++)
printf("%c", x); // int → char อัตโนมัติ
// Explicit (Cast ชัดเจน)
for (int x = 97; x <= 122; x++)
printf("%c", (char)x); // Cast ว่าเป็น char
ข้อควรระวัง
| สถานการณ์ | ปัญหา | แก้ไข |
|---|---|---|
| Float → Int | Truncate ทศนิยม | ใช้ round()/lrint() ถ้าต้องการปัด |
| Large → Small Int | Overflow (Wrap around) | Check Range ก่อน Cast |
| Signed ↔ Unsigned | ค่าติดลบกลายใหญ่มาก | หลีกเลี่ยง ผสม Signed/Unsigned |
| Pointer Cast | Alignment, Strict Aliasing | ใช้ union หรือ memcpy() |
Best Practice
- ให้ Implicit Conversion ทำงาน (ปลอดภัยกว่า)
- ใช้ Explicit Cast **เฉพาะเมื่อจำเป็น** และ Comment ทำไม
- Enable Compiler Warnings:
-Wall -Wextra -Wconversion - ใช้
static_castใน C++ (ปลอดภัยกว่า C-style Cast)