不同的系統中,C++整型變量中的長度位數是不同的,通常,在老式的IBM PC中,int 的位數為16位(與short相同),而在WINDOWS XP,Win7,vax等很多其他的微型計算機中,為32位(與long 相同)。這點在遷移別人的程序中要注意!!!看別人用的什么系統,自己用的什么系統!
例如,如果獲取來自64位win10系統中整型數據的長度,代碼如下:
#include<iostream> using namespace std; #include<climits> int main() { int n_int = INT_MAX; short n_short = SHRT_MAX; long n_long = LONG_MAX; long long n_llong = LLONG_MAX; cout << "int is " << sizeof (n_int) << " bytes." << endl; cout << "short is " << sizeof n_short << " bytes."<< endl; cout << "long is " << sizeof n_long << " bytes." << endl; cout << "long long is " << sizeof n_llong << " bytes." << endl; cout << endl; cout << "Maxium values :" << endl; cout << "int: " << n_int << endl; cout << "short: " << n_short << endl; cout << "long: " << n_long << endl; cout << "long long: " << n_llong << endl; cout << "Minimum values :" << INT_MIN<< endl; cout << "Bits per byte = " << CHAR_BIT << endl; cin.get(); return 0; }
其中,頭文件包含了關於整型限制的信息,具體的說,他定義了各種限制的符號名稱。如INT_MAX表示int 的最大取值,CHAR_BIT為字節的位數。
下圖為程序的運行結果: