首页 > 解决方案 > 我在 [int,float,char 等] 中在 C++ 中命令不同值时得到相同的值

问题描述

输入

int main()
{
    int a; //declaration
    a=15; //initialisation

    cout<<"sizeofint"<<sizeof(a)<<endl\n;
    
    float b;
    cout<<"size of float"<<sizeof(b)<<endl;

    char c;
    cout<<"size of char"<<sizeof(c)<<endl;

    bool d;
    cout<<"size of bool"<<sizeof(d)<<endl;

输出

size of int4
size of float4
size of char1
size of bool1

另一个例子

int a; //declaration
    a=21; //initialisation

    cout<<"sizeofint"<<sizeof(a)<<endl\n;
    
    float b;
    cout<<"size of float"<<sizeof(b)<<endl;

    char c;
    cout<<"size of char"<<sizeof(c)<<endl;

    bool d;
    cout<<"size of bool"<<sizeof(d)<<endl;

输出

size of int4
size of float4
size of char1
size of bool1

两个输出都一样!!!为什么?

标签: c++

解决方案


我认为您认为声明的工作方式存在误解。无论您输入的值有多大int(即使它超出了它的范围)编译器仍然会保留相同数量的字节,这也取决于您的操作系统架构(通常是32-bit64-bit)。例如,size_t在一个32-bit系统中有 4 个字节大小,而64-bit它有 8 个字节大小(对于任何指针也是如此)。对于int值,它默认为 4 个字节(在 ILP64 接口中,它的大小将是原来的两倍!)。Sizeof()返回为某个变量保留了多少内存(以字节为单位)。


推荐阅读