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

การแปลงชนิดข้อมูล (Typecasting) ในภาษา C

Typecasting คือการแปลงชนิดข้อมูลหนึ่งเป็นอีกชนิดหนึ่ง แบ่งเป็น 2 ประเภท

1. Implicit Type Casting (การแปลงโดยอัตโนมัติ)

คอมไพเลอร์ทำการแปลงเอง เมื่อนิพจน์มีตัวแปรหลายชนิด เพื่อป้องกันการสูญเสียข้อมูล

ตัวอย่าง

#include <stdio.h>
int main() {
    int a = 10;
    char b = 'S';
    float c = 2.88;
    a = a + b;
    printf("Implicit conversion from character to integer : %d\n", a);
    c = c + a;
    printf("Implicit conversion from integer to float : %f\n", c);
    return 0;
}

ผลลัพธ์

Implicit conversion from character to integer : 93
Implicit conversion from integer to float : 95.879997

2. Explicit Type Casting (การแปลงโดยผู้ใช้)

ผู้เขียนโค้ดบังคับแปลงชนิดข้อมูล เรียกว่า Typecasting

รูปแบบไวยากรณ์

(type) expression

ตัวอย่าง

#include <stdio.h>
int main() {
    float c = 5.55;
    int s = (int)c + 1;
    printf("Explicit Conversion : %d\n", s);
    return 0;
}

ผลลัพธ์

Explicit Conversion : 6