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

相关推荐
StudyWinter39 分钟前
【C++】仿函数和回调函数
开发语言·c++·回调函数·仿函数
君鼎2 小时前
Effective C++ 条款55:熟悉Boost库
c++
Zafir20243 小时前
Qt实现TabWidget通过addTab函数添加的页,页内控件自适应窗口大小
开发语言·c++·qt·ui
阿巴~阿巴~4 小时前
深入解析C++非类型模板参数
开发语言·c++
多吃蔬菜!!!4 小时前
vscode 搭建C/C++开发环境搭建(linux)
linux·c语言·c++
小指纹6 小时前
河南萌新联赛2025第(六)场:郑州大学
java·开发语言·数据结构·c++·算法
岁忧6 小时前
(nice!!!)(LeetCode 每日一题) 1277. 统计全为 1 的正方形子矩阵 (动态规划)
java·c++·算法·leetcode·矩阵·go·动态规划
咔咔咔的6 小时前
679. 24 点游戏
c++
the sun347 小时前
Reactor设计模式及其在epoll中的应用
linux·运维·服务器·c++
Davis_12197 小时前
代码随想录算法训练营27天 | 56. 合并区间、738.单调递增的数字、968.监控二叉树(提高)
数据结构·c++·算法·leetcode·贪心算法