C++中可用的整型类型有五种,由小到大分别是char(也可以看成一种单字节的整型)、short、int、long、long long。它们使用不同数目的位来存储整型值。char在任何系统中都是单字节8位,但是short总是16位,int总是32位吗?并非那么简单,没有一种选择能够满足所有计算机的设计要求。C++提供了一种灵活的标准,它确保了最小长度(从C语言借鉴而来),如下所示:
(1). short至少16位;
(2). int 至少short一样长;
(3). long 至少32位,且至少与int一样长;
(4). long long 至少64位,且至少与long一样长。
查看自己系统上整型类型的大小和范围,我们可以借助sizeof运算符和limits头文件来查看。
以下是查看的代码:
#include <iostream>
#include <climits>
using namespace std;
int main(void)
{
cout << "signed char is " << sizeof(char) << " bytes." << endl;
cout << "signed int is " << sizeof(int) << " bytes." << endl;
cout << "signed short is " << sizeof(short) << " bytes." << endl;
cout << "signed long is " << sizeof(long) << " bytes." << endl;
cout << "signed long long is " << sizeof(long long) << " bytes." << endl << endl;
//下面宏都是climits头文件中所定义,可打开改头文件观察
cout << "Maxinum values and Mininum values: " << endl;
cout << "signed char : " << SCHAR_MIN << " -- " << SCHAR_MAX << endl;
cout << "signed int : " << INT_MAX << " -- "<< INT_MIN << endl;
cout << "signed short : " << SHRT_MIN << " -- " << SHRT_MAX << endl;
cout << "signed long : " << LONG_MIN << " -- " << LONG_MAX << endl;
cout << "signed long long : " << LLONG_MIN << " -- " << LLONG_MAX << endl;
return 0;
}
运行截图: