ชนิดข้อมูลพื้นฐานใน C++
- int - จำนวนเต็ม ปกติใช้ 4 ไบต์
- float - จำนวนจริงความแม่นยำเดี่ยว (single precision) ปกติ 4 ไบต์
- double - จำนวนจริงความแม่นยำคู่ (double precision) ปกติ 8 ไบต์
- char - ตัวอักษร ปกติ 1 ไบต์
ตัวดำเนินการ sizeof
sizeof ใช้หาขนาดของชนิดข้อมูลหรือตัวแปรในหน่วยไบต์ เป็นตัวดำเนินการที่ทำงานระหว่างคอมไพล์ (compile-time)
รูปแบบ: sizeof(ชนิดข้อมูล) หรือ sizeof ตัวแปร
โปรแกรมตัวอย่าง
#include <iostream>
using namespace std;
int main() {
cout << "Size of int is " << sizeof(int) << " bytes" << endl;
cout << "Size of float is " << sizeof(float) << " bytes" << endl;
cout << "Size of double is " << sizeof(double) << " bytes" << endl;
cout << "Size of char is " << sizeof(char) << " byte" << endl;
return 0;
}
ผลลัพธ์ (ตัวอย่างบนระบบ 64-bit ทั่วไป)
Size of int is 4 bytes Size of float is 4 bytes Size of double is 8 bytes Size of char is 1 byte
หมายเหตุ: ขนาดจริงอาจแตกต่างไปตามแพลตฟอร์มและคอมไพเลอร์ ใช้ sizeof เพื่อตรวจสอบขนาดจริงบนระบบของคุณ