Latest web development tutorials

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++運算符