![4b307f356b9237e0d46969a092ac2c1e.png](https://i-blog.csdnimg.cn/blog_migrate/b336368eeacf99d1f31df73787233a5c.jpeg)
C++提供了丰富的内置数据类型,用户也可以自定义数据类型,下面是5种基本数据类型:
- 布尔型:bool
- 字符型:char
- 整型:int
- 浮点型:float
- 双浮点型:double
基本数据类型还可以使用下面的类型修饰符进行修饰:
- 有符号:signed
- 无符号:unsigned
- 短整型:short
- 长整型:long
int 是基本的整数类型,默认是有符号的(signed ),unsigned 表示无符号,无符号值可以避免误存负数, 同时扩大了正数的表示范围。
short 和 long 是在 int 的基础上进行的扩展,使用 short int 可以节省内存,long int 则可以表示更大的值。
1、数据类型的大小
sizeof() 是一个判断数据类型或者表达式长度的运算符,以字节为单位。
C语言运算符sizeof的用法
![6d729d9020329f8ea7668b1904b95b6c.png](https://i-blog.csdnimg.cn/blog_migrate/a682dbf762beef34d3384dee4e4c3a65.jpeg)
2、数据类型的范围
一般数值类型的最小值和最大值与平台相关,C++11中通过模板类 std::numeric_limits,提供了基础算术类型的极值等属性信息,用于取代 和 ,浮点常数定义于 和 。
template numeric_limits;
The numeric_limits class template provides a standardized way to query various properties of arithmetic types.
代码如下:
#include using namespace std;int main(){ cout << "sizeof(bool) : " << sizeof(bool) << endl; cout << "sizeof(char) : " << sizeof(char) << endl; cout << "sizeof(int) : " << sizeof(int) << endl; cout << "sizeof(unsigned int) : " << sizeof(unsigned int) << endl; cout << "sizeof(short int) : " << sizeof(short int) << endl; cout << "sizeof(long int) : " << sizeof(long int) << endl; cout << "sizeof(float) : " << sizeof(float) << endl; cout << "sizeof(double) : " << sizeof(double) << endl; cout << "min(bool) : " << numeric_limits::min() << endl; cout << "min(int) : " << numeric_limits::min() << endl; cout << "min(unsigned int) : " << numeric_limits::min() << endl; cout << "min(short int) : " << numeric_limits::min() << endl; cout << "min(long int) : " << numeric_limits::min() << endl; cout << "min(float) : " << numeric_limits::min() << endl; cout << "min(double) : " << numeric_limits::min() << endl; cout << "max(bool) : " << numeric_limits::max() << endl; cout << "max(int) : " << numeric_limits::max() << endl; cout << "max(unsigned int) : " << numeric_limits::max() << endl; cout << "max(short int) : " << numeric_limits::max() << endl; cout << "max(long int) : " << numeric_limits::max() << endl; cout << "max(float) : " << numeric_limits::max() << endl; cout << "max(double) : " << numeric_limits::max() << endl; return 0;}
运行结果如下:
![ddae26e83b55ea6593fc40aaf40504d8.png](https://i-blog.csdnimg.cn/blog_migrate/5d34e4dba7ff4df80290bf097ab6b657.jpeg)
C++基本数据类型的大小和极值范围,总结如下表所示:
![6d729d9020329f8ea7668b1904b95b6c.png](https://i-blog.csdnimg.cn/blog_migrate/a682dbf762beef34d3384dee4e4c3a65.jpeg)
相关阅读
初识C语言指针
深入理解C语言的指针
C++中指针与引用的区别
C++的友元函数和友元类
C++类的三种继承方式:public/protected/private