在c++中可以通过sizeof关键字来求出各数据类型大小;代码如下:
int main()
{
cout <<"int类型:"<<"大小:"<<sizeof(int) <<" int最小值:"<< INT_MIN<<" int最大值:"<<INT_MAX<<endl;
cout << " lont int类型:" << "大小:" << sizeof(long) << " long int最小值:" << LONG_MIN << " long int最大值:" << LONG_MAX << endl;
cout << " lont long int类型:" << "大小:" << sizeof(long long int) << " long long int最小值:" << LLONG_MIN << " long long int最大值:" << LLONG_MAX << endl;
system("pause");
return 0;
}
其最终结果为:
int类型:大小:4 int最小值:-2147483648 int最大值:2147483647
lont int类型:大小:4 long int最小值:-2147483648 long int最大值:2147483647
lont long int类型:大小:8 long long int最小值:-9223372036854775808 long long int最大值:9223372036854775807
上述的INT_MIN等都是c++语言中提前宏定义好的;
其计算方式为:例如当求INT_MAX时,int占据4个字节,因此占据32位,第一位为符号位,因此后面31位可以求得的最大值为
2
31
2^{31}
231-1可以得到。
该结果是在x86系统下,即32位编译系统下的结果;
对32位编译系统和64位编译系统(x64系统下)的结果分类可得:
1、32位编译系统中:
long 占4字节 int 占4字节 long int 占4字节
2、64位编译系统中;
long 占8字节 int 占4字节 long int 占8字节
3、32位和64位编译系统中;
long long int 在32位和64位编译系统中,都占8字节;