使用 C++ sizeof 运算符来计算 int, float, double 和 char 变量占用的空间大小。
sizeof 运算符语法格式:
sizeof(dataType);
注意:不同系统计算结果可能不一样。
#include <iostream>
using namespace std;
 
int main() 
{    
    cout << "char: " << sizeof(char) << " 字节" << endl;
    cout << "int: " << sizeof(int) << " 字节" << endl;
    cout << "float: " << sizeof(float) << " 字节" << endl;
    cout << "double: " << sizeof(double) << " 字节" << endl;
 
    return 0;
}以上程序执行输出结果为:
char: 1 字节 int: 4 字节 float: 4 字节 double: 8 字节