C++ sizeof 運算符

C++ 運算符 C++ 運算符

sizeof 是一個關鍵字,它是一個編譯時運算符,用於判斷變數或數據類型的位元組大小。

sizeof 運算符可用於獲取類、結構、共用體和其他用戶自定義數據類型的大小。

使用 sizeof 的語法如下:

sizeof (data type)

其中,data type 是要計算大小的數據類型,包括類、結構、共用體和其他用戶自定義數據類型。

請嘗試下麵的實例,理解 C++ 中 sizeof 的用法。複製並黏貼下麵的 C++ 程式到 test.cpp 檔中,編譯並運行程式。

#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;
}

當上面的代碼被編譯和執行時,它會產生下列結果,結果會根據使用的機器而不同:

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

C++ 運算符 C++ 運算符