C++ 整型长度的获取 不同的系统

不同的系统中,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为字节的位数。

下图为程序的运行结果:

原文地址:https://www.cnblogs.com/carlber/p/9839856.html