原始内置类型

C++中定义的原始类型包括算术类型(arithmetic)和一个特殊的void。算术类型就是指字符,整型,布尔和浮点数等。

算术类型

每种类型的大小是机器相关的,标准只是定义了最小Size

比如,char只是保证了能容纳下一个机器的基本字符,一般是一个机器byte。shortint都是最小16 bits,long最小是32 bits,long long最小是64 bits。(long long 其实是C++ 11才加入的

另外,宽字符有 wchar_t,Unicode字符有 char16_tchar32_t

有符号和无符号

除了bool和扩展的字符类型,其他整型都分有符号和无符号。像intlonglong long都是有符号的,如果加上unsigned就是无符号的。另外,usigned int可以缩写成usigned

  • singed : 可以表示正或负
  • unsinged : >=0

比较特殊的是char,标准里char可以是有符号,也可以是无符号,看编译器实现。

使用建议

实际编程中,intlong一般一样长,所以短的用short,一般的用int,特大的long long

浮点的直接使用double吧,因为float精度不好,且不见得比double快。当然,如果要特别精确,使用long double

类型转换

后面的文章会有进一步讨论这个问题,这里简单介绍。

bool b = 42; // b is true; 非布尔算术值赋值给bool, 等于0是false,其他是true
int i = b; // i is 1;bool赋值给算术值,false是0,true是1。
i = 3.14;
double pi = i;
unsigned char c = -1; // assuming 8-bit chars, c has value 255 signed 
char c2 = 256; // assuming 8-bit chars, the value of c2 is undefined

因此,

double d = 0.1;
bool b = d; // b is true

越界的值给unsigned,取模;越界的值给signed,undefined。 参见:StackOverflow

不要把让负数赋值给unsigned。

unsigned u = 10, u2 = 42;
std::cout << u - u2 << std::endl;

如果一个算术表达式里同时有 unsigned 和 int,int会变成 unsigned。

int i = -40;
unsigned u = 42;
unsigned i2 = i;
std::cout << i2 << std::endl; // 4294967256
std::cout << i + u << std::endl; // 2 

字面常量

字符和字符串:

前缀 类型
u char16_t
U char32_t
L wchar_t
u8 char (utf-8, string literals only)

(u8, u, U都是 C++ 11 才加入的)

整型:

后缀 最小类型
u or U unsigned
l or L long
ll or LL long long

浮点:

后缀 最小类型
f or F float
l or L long double
L'a' // wide character literal, type is wchar_t
u8"hi!" // utf-8 string literal (utf-8 encodes a Unicode character in 8 bits) 
42ULL // unsigned integer literal, type is unsigned long long
1E-3F // single-precision floating-point literal, type is float 
3.14159L // extended-precision floating-point literal, type is long double