C++ 快速導覽 - sizeof 運算

C++ 的 sizeof 運算子的用途作為計算物件或資料型態所佔的位元組數 (byte) ,有以下三種形式

  • sizeof (type name);
  • sizeof (expr);
  • sizeof expr;


例如以下程式計算出各種整數型態宣告組合所佔的位元組數
#include <iostream>

int main()
{
    std::cout << "short : " << sizeof(short) << std::endl;
    std::cout << "short int : " << sizeof(short int) << std::endl;
    std::cout << "signed short : " << sizeof(signed short) << std::endl;
    std::cout << "signed short int : " << sizeof(signed short int) << std::endl;
    std::cout << "unsigned short : " << sizeof(unsigned short) << std::endl;
    std::cout << "unsigned short int : " << sizeof(unsigned short int) << std::endl;
    std::cout << "int : " << sizeof(int) << std::endl;
    std::cout << "signed : " << sizeof(signed) << std::endl;
    std::cout << "signed int : " << sizeof(signed int) << std::endl;
    std::cout << "unsigned : " << sizeof(unsigned) << std::endl;
    std::cout << "unsigned int : " << sizeof(unsigned int) << std::endl;
    std::cout << "long : " << sizeof(long) << std::endl;
    std::cout << "long int : " << sizeof(long int) << std::endl;
    std::cout << "signed long : " << sizeof(signed long) << std::endl;
    std::cout << "signed long int : " << sizeof(signed long int) << std::endl;
    std::cout << "unsigned long : " << sizeof(unsigned long) << std::endl;
    std::cout << "unsigned long int : " << sizeof(unsigned long int) << std::endl;
    return 0;
}
 
/* 《程式語言教學誌》的範例程式
    http://pydoing.blogspot.com/
    檔名:sizeofint.cpp
    功能:計算 int 所佔的位元組數
    作者:張凱慶
    時間:西元 2010 年 10 月 */


編譯後執行,結果如下



中英文術語對照
位元組數byte


您可以繼續參考
運算式
型態轉換


相關目錄
回 C++ 快速導覽
回 C++ 教材
回首頁


參考資料
C++ reference
cplusplus.com
Cprogramming.com C++ Tutorial

C++ Primer, Fourth Edition, Stanley B. Lippman...


本文於 2013 年 1 月更新

沒有留言: