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

Sizeof Operator ใน C++


นิยาม

sizeof เป็น keyword แต่เป็น compile-time operator หาขนาดใน bytes ของ variable หรือ data type

Syntax

sizeof (data type)

รองรับ classes, structures, unions, user-defined types

กฎพิเศษ

  • sizeof(char) เสมอ = 1
  • Array → ขนาดทั้งหมดใน bytes (ไม่ใช่ขนาด pointer)

ตัวอย่าง

#include <iostream>
using namespace std;

int main() {
    cout << "Size of char: " << sizeof(char) << endl;
    cout << "Size of int: " << sizeof(int) << endl;
    cout << "Size of short int: " << sizeof(short int) << endl;
    cout << "Size of long int: " << sizeof(long int) << endl;
    cout << "Size of float: " << sizeof(float) << endl;
    cout << "Size of double: " << sizeof(double) << endl;
    cout << "Size of wchar_t: " << sizeof(wchar_t) << endl;
    return 0;
}

ผลลัพธ์ (ตัวอย่าง 64-bit system)

Size of char: 1
Size of int: 4
Size of short int: 2
Size of long int: 4
Size of float: 4
Size of double: 8
Size of wchar_t: 4

หมายเหตุ: ขนาดขึ้นกับ platform/compiler เนื้อหาทับซ้อน ID 1004083483