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++课程

相关推荐
古月-一个C++方向的小白6 小时前
C++11之lambda表达式与包装器
开发语言·c++
tanyongxi668 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++
斯是 陋室10 小时前
在CentOS7.9服务器上安装.NET 8.0 SDK
运维·服务器·开发语言·c++·c#·云计算·.net
tju新生代魔迷10 小时前
C++:list
开发语言·c++
HHRL-yx11 小时前
C++网络编程 5.TCP套接字(socket)通信进阶-基于多线程的TCP多客户端通信
网络·c++·tcp/ip
tomato0911 小时前
河南萌新联赛2025第(一)场:河南工业大学(补题)
c++·算法
每一天都要努力^13 小时前
C++拷贝构造
开发语言·c++
NoirSeeker15 小时前
在windows平台上基于OpenHarmony sdk编译三方库并暴露给ArkTS使用(详细)
c++·windows·arkts·鸿蒙·交叉编译
落羽的落羽15 小时前
【C++】(万字)一文看懂“类与对象”
c++
闻缺陷则喜何志丹16 小时前
【带权的并集查找】 P9235 [蓝桥杯 2023 省 A] 网络稳定性|省选-
数据结构·c++·蓝桥杯·洛谷·并集查找