C/C++ 各类型int、long、double、char、long long取值范围(基本类型的最大最小值)

发布时间 2023-04-30 14:32:59作者: bujidao1128

做题的时候经常会使用到数据类型的最大最小值(如int, long, long long, char等),我也查了很多次,这次就记下来当笔记吧。

参考了C++ prime plus、各个博客、教程和c++官网,对C/C++中各个类型int、long、double、char、long long等基本类型的取值范围即最大最小值总结如下:

1字节 = 8位,“位”是计算机内存的基本单元

注意:
不同的操作系统和编译器会导致变量的取值范围不同,各位可以使用以下代码查看自己操作系统的变量取值范围:

#include<iostream>  
#include<string>  
#include <limits>  
using namespace std;  
  
int main(){  
    cout << "[type] \t\t" << "[所占字节数]\t[最大值]\t\t[最小值]"<< endl;  
    cout << "bool: \t\t" <<  sizeof(bool) << "\t\t" << (numeric_limits<bool>::max)() << "\t\t\t" << (numeric_limits<bool>::min)() << endl;  
    cout << "char: \t\t" <<  sizeof(char) << "\t\t" << CHAR_MAX << "\t\t\t" << CHAR_MIN << endl;  
    cout << "signed char: \t"  << sizeof(signed char) << "\t\t" << SCHAR_MAX << "\t\t\t" << SCHAR_MIN << endl;  
    cout << "unsigned char: \t" <<  sizeof(unsigned char) << "\t\t" << UCHAR_MAX << "\t\t\t" << (numeric_limits<unsigned char>::min)() << endl;  
    cout << "wchar_t: \t" << sizeof(wchar_t) << "\t\t" << (numeric_limits<wchar_t>::max)() << "\t\t\t" << (numeric_limits<wchar_t>::min)() << endl;  
    cout << "short: \t\t" <<  sizeof(short) << "\t\t" << SHRT_MAX << "\t\t\t" << SHRT_MIN << endl;  
    cout << "int: \t\t" <<  sizeof(int) << "\t\t" << INT_MAX << "\t\t" << INT_MIN << endl;  
    cout << "unsigned: \t" << sizeof(unsigned) << "\t\t" << UINT_MAX << "\t\t" << (numeric_limits<unsigned>::min)() << endl;  
    cout << "long: \t\t" << sizeof(long) << "\t\t" << LONG_MAX << "\t\t" << LONG_MIN << endl;  
    cout << "unsigned long: \t" << sizeof(unsigned long) << "\t\t" << ULONG_MAX << "\t\t" << (numeric_limits<unsigned long>::min)() << endl;  
    cout << "long long: \t" <<  sizeof(long long) << "\t\t" << LLONG_MAX << "\t" << LLONG_MIN << endl;  
    cout << "double: \t" << sizeof(double) << "\t\t" << (numeric_limits<double>::max)() << "\t\t" << (numeric_limits<double>::min)() << endl;
	 cout << "long double: \t" <<  sizeof(long double) << "\t\t" << (numeric_limits<long double>::max)() << "\t\t" << (numeric_limits<long double>::min)() << endl;    
    cout << "float: \t\t" <<  sizeof(float) << "\t\t" << (numeric_limits<float>::max)() << "\t\t" << (numeric_limits<float>::min)() << endl;  
    cout << "size_t: \t" << sizeof(size_t) << "\t\t" << (numeric_limits<size_t>::max)() << "\t\t" << (numeric_limits<size_t>::min)() << endl;  
    cout << "string: \t" << sizeof(string) << endl;  
    cout << "[type] \t\t" << "[所占字节数]\t[最大值]\t\t[最小值]"<< endl;   
    return 0;  
}

该代码是我查看了其他文章和教程的代码后写的,我个人认为那些代码有些乱且有错,同时我也加上了他们都漏掉的long long数据类型的取值范围。

接下来是C++官网的宏定义数据表,作为参考:
头文件:#include 或 #include <limits.h>

教程中的表: