【C++】【基础语法】sizeof关键字

sizeof关键字

sizeof关键字用来计算数据类型或变量在内存中的存储空间,不同操作系统或编译器下结果可能存在差异。

  • 计算数据类型所占内存大小

    可以使用sizeof (type)来计算type类型所占内存空间的大小,注意括号不能省略;例如

    sizeof (int);
    
  • 计算变量所占内存大小

    可以使用sizeof data来计算变量data所占内存空间的大小,可以省略括号;例如

    int data = 0;
    sizeof data;
    

实例:

int bool_size = sizeof (bool);
    int char_size = sizeof (char);
    int short_size = sizeof (short);
    int int_size = sizeof (int);
    int long_size = sizeof (long);
    int longlong_size = sizeof (long long);
    int float_size = sizeof(float);
    int double_size = sizeof(double);
    std::cout << "bool 类型所占内存空间大小为: " << bool_size << " bytes" << std::endl;
    std::cout << "char 类型所占内存空间大小为: " << char_size << " bytes" << std::endl;
    std::cout << "int 类型所占内存空间大小为: " << short_size << " bytes" << std::endl;
    std::cout << "long 类型所占内存空间大小为: " << long_size << " bytes" << std::endl;
    std::cout << "long long 类型所占内存空间大小为: " << longlong_size << " bytes" << std::endl;
    std::cout << "float 类型所占内存空间大小为: " << float_size << " bytes" << std::endl;
    std::cout << "double 类型所占内存空间大小为: " << double_size << " bytes" << std::endl;

    int data = 0;
    int data_size = sizeof data;
    std::cout << "变量data所占内存空间大小为: " << data_size << "bytes" << std::endl;

以上程序输出为:

bool 类型所占内存空间大小为: 1 bytes     
char 类型所占内存空间大小为: 1 bytes     
int 类型所占内存空间大小为: 2 bytes      
long 类型所占内存空间大小为: 4 bytes     
long long 类型所占内存空间大小为: 8 bytes
float 类型所占内存空间大小为: 4 bytes    
double 类型所占内存空间大小为: 8 bytes   
变量data所占内存空间大小为: 4bytes 
posted @ 2023-05-31 17:12  醉梦临川  阅读(121)  评论(0)    收藏  举报