基本数据类型
整型,字符型,布尔型,浮点型
基本数据类型最小长度
C/C++标准只定义了最低的位数,而不是必需的固定位数
- bool 布尔型
- char 字符型 8位
- wchar_t 宽字符型 16位
- short 短整型 16位
- int 整形 16位
- long 长整形 32位
- float 单精度浮点型 6为有效数字
- double 双精度浮点型 10位有效数字
- long double 扩展精度浮点型 10位有效数字
这些类的长度并不一定是固定的,跟系统平台有关。
char类型
- char默认的既不是有符号,也不是无符号,是不确定,所以如果用作运算的话,要指定signed char或者unsigned char
- char有无符号不影响ASCII码的值
- cout输出char时,打印的是ASCII码,而不是具体数值。而其他类型的是打印数值,例如int类型
signed nChar = 100;
unsigned uChar = 100;
cout << nChar << ", " << uChar << endl;
输出:d,d
float, double
float 单精度浮点型,最少32位,通常32位,6为有效数字
double 双精度浮点型,最少48位,通常64位, 10位有效数字
long double,扩展精度浮点型,通常为80,96或128位,10位有效数字
常量的类型
- L/l表示long类型,如100L。
- U/u表示unsigned int类型,如100U
- UL表示unsigned long类型,如100UL
- ULL表示unsigned long long类型,如100ULL
- 8进制表示法,第一位0,后面位数1-7,如042,值是34
- 16进制表示法,0x/0X开头,其他位数0-f,如0xA5,值是165
数据类型平台适配性
一般基本数据类型是,但是它们的类型长度在不同平台可能不一样
- signed char 和 unsigned char
- short 和 unsigned short
- int 和 unsigned int
- long 和 unsigned long
int8_t,uint8_t等
这些是标准中指定的代表位数的类型
- int8_t 和 uint8_t 表示8位整型
- int16_t 和 uint16_t 表示16位整型
- int32_t 和 uint32_t 表示32位整型
- int64_t 和 uint64_t 表示64位整型
它们的实现其实是基于typedef定义而来的,在stdint.h头文件中有定义。
typedef signed char int8_t;
typedef short int16_t;
typedef int int32_t;
typedef long long int64_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
因为它是一个标准头文件,其他平台stdint.h中的这些定义可能会不一样,但是至少会确保定义的这些类型,位数是对应的,所以可以用它们来适配类型长度固定的整型。
例如有的平台是这样的typedef short int16_t;
而有的平台是这样的typedef int int16_t;
但它们都指定了int16_t这个类型是16位的整数,只不过一个是用int实现的,一个是用short实现的。
- int8_t表示这是一个8位整型的typedef定义,通用命名是*_t。
__int8、__int16、__int32、__int64
这是微软专用的用来表达8位,16位,32位,64位的整数,其他平台就无法识别了。
整数类型的适配方案
int8_t这种是标准定义的类型,但却不能保证所有平台都会使用这个标准,例如微软就定义它的__int8这种类型。那为了适配,我们需要重新定义它。
//如果是微软编译器平台,则使用微软提供的整型定义,否则使用标准的整型定义
#ifdef _MSC_VER
typedef signed __int8 int8;
typedef unsigned __int8 uint8;
typedef signed __int16 int16;
typedef unsigned __int16 uint16;
typedef signed __int32 int32;
typedef unsigned __int32 uint32;
typedef signed __int64 int64;
typedef unsigned __int64 uint64;
#else
#include <stdint.h>
typedef int8_t int8;
typedef uint8_t uint8;
typedef int16_t int16;
typedef uint16_t uint16;
typedef int32_t int32;
typedef uint32_t uint32;
typedef int64_t int64;
typedef uint64_t uint64;
#endif
size_t
- size_t表示无符号的整型,它是用来记录大小的数据类型。在32位系统中,size_t是4个字节,64位系统中,size_t是8个字节。
- size_t一般是用sizeof操作符得到的,表示大小。
- size_t的定义是
#ifndef _SIZE_T_DEFINED
#ifdef _WIN64
typedef unsigned __int64 size_t;
#else
typedef _W64 unsigned int size_t;
#endif
#define _SIZE_T_DEFINED
#endif
wchar_t
表示双字节或宽字节的字符类型,用于表达其他一些字符,例如中文字符。
http://blog.csdn.net/lishuzhai/article/details/50595498
char16_t,char32_t
c++11新增的字符型,分别是16位和32位的无符号的类型,专门用于表示字符
char16_t用法
使用前缀u
char16_t ch1 = u'g'; 用16位表示的字符g,
char16_t* str1 = u'be good'; 用16位字符表示的字符串be good
char32_t用法
使用前缀U
char32_t ch1 = U'g'; 用32位表示的字符g
char32_t* str1 = u'be good'; 用32位字符表示的字符串be good