C++中获取系统整型的极限长度

C++中获取系统整型的极限长度

要知道系统中整数的最大长度,可以在程序中使用C++工具来检查类型的长度。首先,sizeof运算符返回类型或变量的长度,单位为字节(运算符是内置的语言元素,对一个或多个数据进行运算,并生成一个值。例如,加号运算符+将两个值相加)。前面说过,"字节"的含义依赖于实现,因此在一个系统中,两字节的int可能是16位,而在另一个系统中可能是32位。其次,头文件 climits(在老式实现中为 limits,h)中包含了关于整型限制的信息。具体地说,它定义了表示各种限制的符号名称。例如,INTMAX为 int的最大取值,CHAR_BIT为字节的位数。程序清单3.1演示了如何使用这些工具。该程序还演示如何初始化,即使用声明语句将值赋给变量。

复制代码
// limits.cpp -- some integer limits
#include <iostream>
#include <climits>              // use limits.h for older systems
int main()
{
    using namespace std;
    int n_int = INT_MAX;        // initialize n_int to max int value
    short n_short = SHRT_MAX;   // symbols defined in climits file
    long n_long = LONG_MAX;
	long long n_llong = LLONG_MAX;

    // sizeof operator yields size of type or of variable
    cout << "int is " << sizeof (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 << "Maximum values:" << endl;
    cout << "int: " << n_int << endl;
    cout << "short: " << n_short << endl;
    cout << "long: " << n_long << endl;
    cout << "long long: " << n_llong << endl << endl;

    cout << "Minimum int value = " << INT_MIN << endl;
    cout << "Bits per byte = " << CHAR_BIT << endl;
	// cin.get();
    return 0;
}

注意:如果您的系统不支持类型1onglong,应删除使用该类型的代码行。下面是程序清单 3.1中程序的输出:

int is 4 bytes.

short is 2 bytes.

long is 4 bytes.

long long is 8 bytes.

Maximum values :

int:2147483647

short:32767

long:2147483647

long long:9223372036854775807

Minimum int value=-2147483648Bits per byte=8

这些输出来自运行64位 Windows7的系统。

对C++感兴趣的朋友点这里:C/C++课程

相关推荐
AA陈超12 分钟前
虚幻引擎UE5专用服务器游戏开发-20 添加基础能力类与连招能力
c++·游戏·ue5·游戏引擎·虚幻
mit6.82433 分钟前
[Meetily后端框架] AI摘要结构化 | `SummaryResponse`模型 | Pydantic库 | vs marshmallow库
c++·人工智能·后端
R-G-B40 分钟前
【02】MFC入门到精通——MFC 手动添加创建新的对话框模板
c++·mfc·mfc 手动添加创建新的对话框
linux kernel1 小时前
第七讲:C++中的string类
开发语言·c++
Tipriest_1 小时前
[数据结构与算法] 优先队列 | 最小堆 C++
c++·优先队列·数据结构与算法·最小堆
宛西南浪漫戈命1 小时前
Centos 7下使用C++使用Rdkafka库实现生产者消费者
c++·centos·linq
帅_shuai_3 小时前
C++ 模板参数展开
c++
chilavert3183 小时前
技术演进中的开发沉思-30 MFC系列:五大机制
c++·windows
七七七七074 小时前
C++类对象多态底层原理及扩展问题
开发语言·c++
雨落倾城夏未凉4 小时前
8.Qt文件操作
c++·后端·qt