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 小时前
【算法专题】滑动窗口:从“无重复字符”到“字母异位词”的深度剖析
java·开发语言·c++·人工智能·python·算法·ai
我叫袁小陌2 小时前
C++多线程全面详解
开发语言·c++
m0_748250032 小时前
C++ 官方文档与标准
开发语言·c++
matlabgoodboy3 小时前
程序代做python代编程matlab定制代码编写C++代写plc设计java帮做
c++·python·matlab
DYS_房东的猫3 小时前
《 C++ 零基础入门教程》第6章:模板与 STL 算法 —— 写一次,用万次
开发语言·c++·算法
点云SLAM3 小时前
C++ 静态初始化顺序问题(SIOF)和SLAM / ROS 工程实战问题
开发语言·c++·slam·静态初始化顺序问题·工程实战技术·c++static 关键字
pen-ai4 小时前
打通 Python 与 C++ 的参数传递机制
开发语言·c++·python
王老师青少年编程4 小时前
信奥赛C++提高组csp-s之KMP算法详解
c++·kmp·字符串匹配·csp·信奥赛·csp-s·提高组
喵星人工作室4 小时前
C++传说:神明之剑0.4.5装备机制彻底完成
开发语言·c++·游戏
不会写代码的ys4 小时前
日志库封装(项目通用)
c++