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

相关推荐
小汉堡编程1 小时前
数据结构——vector数组c++(超详细)
数据结构·c++
tan180°6 小时前
MySQL表的操作(3)
linux·数据库·c++·vscode·后端·mysql
彭祥.7 小时前
Jetson边缘计算主板:Ubuntu 环境配置 CUDA 与 cudNN 推理环境 + OpenCV 与 C++ 进行目标分类
c++·opencv·分类
lzb_kkk8 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
胖大和尚10 小时前
clang 编译器怎么查看在编译过程中做了哪些优化
c++·clang
钱彬 (Qian Bin)11 小时前
一文掌握Qt Quick数字图像处理项目开发(基于Qt 6.9 C++和QML,代码开源)
c++·开源·qml·qt quick·qt6.9·数字图像处理项目·美观界面
双叶83611 小时前
(C++)学生管理系统(正式版)(map数组的应用)(string应用)(引用)(文件储存的应用)(C++教学)(C++项目)
c语言·开发语言·数据结构·c++
源代码•宸12 小时前
C++高频知识点(二)
开发语言·c++·经验分享
jyan_敬言13 小时前
【C++】string类(二)相关接口介绍及其使用
android·开发语言·c++·青少年编程·visual studio
liulilittle13 小时前
SNIProxy 轻量级匿名CDN代理架构与实现
开发语言·网络·c++·网关·架构·cdn·通信