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

ชนิดข้อมูล (Data Types) ในภาษา C มีอะไรบ้าง


คำอธิบาย

Data Type (ชนิดข้อมูล) คือการประกาศตำแหน่งหน่วยความจำหรือตัวแปร ข้อมูลมีหลายประเภท เช่น จำนวนเต็ม เศษส่วน จำนวนจริง จำนวน مختلط เวกเตอร์ ตัวอักษร ฯลฯ ในระดับฮาร์ดแวร์ ข้อมูลทั้งหมดเข้ารหัสเป็นบิต 0 และ 1

Built-in Data Types (ชนิดข้อมูลพื้นฐาน)

ในภาษา C มี Built-in Data Types หลักๆ ดังนี้:

  • int (จำนวนเต็ม)
  • float (จำนวนทศนิยม)
  • char (ตัวอักษร)
  • unsigned int, unsigned char
  • long int, double, long double

การใช้งานตัวอย่าง

  • char string, grade = 'A';
  • int count, index = 10;
  • float average = 6.9;

โค้ดตัวอย่าง: หาขนาดของตัวแปรและชนิดข้อมูล

#include <stdio.h>

int main() {
    int x = 10;
    char c;
    printf("Size of variable x = %zu bytes\n", sizeof(x));
    printf("Size of variable c = %zu byte\n", sizeof(c));
    printf("Size of short = %zu bytes\n", sizeof(short));
    printf("Size of int = %zu bytes\n", sizeof(int));
    printf("Size of long = %zu bytes\n", sizeof(long));
    printf("Size of float = %zu bytes\n", sizeof(float));
    printf("Size of double = %zu bytes\n", sizeof(double));
    printf("Size of long double = %zu bytes\n", sizeof(long double));
    printf("Size of char = %zu bytes\n", sizeof(char));
    printf("Size of void = %zu bytes\n", sizeof(void));
    return 0;
}

ผลลัพธ์ตัวอย่าง (ขึ้นอยู่กับระบบ)

Size of variable x = 4 bytes
Size of variable c = 1 byte
Size of short = 2 bytes
Size of int = 4 bytes
Size of long = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of long double = 16 bytes
Size of char = 1 byte
Size of void = 1 byte