C++ sizeof 運算子



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
cpp_operators.htm
廣告