C语言易错剖析(1)-数据类型

C语言易错剖析

int8_t、int16_t、int32_t、int64_t、uint8_t、size_t、ssize_t等数据类型

int_t同类

int_t 为一个结构的标注,可以理解为type/typedef的缩写,表示它是通过typedef定义的,而不是一种新的数据类型。因为跨平台,不同的平台会有不同的字长,所以利用预编译和typedef可以最有效的维护代码。

 int8_t      : typedef signed char;
 uint8_t    : typedef unsigned char;
 int16_t    : typedef signed short ;
 uint16_t  : typedef unsigned short ;
 int32_t    : typedef signed int;
 uint32_t  : typedef unsigned int;
 int64_t    : typedef signed  long long;
 uint64_t  : typedef unsigned long long;
Specifier Common Equivalent Signing Bits Bytes Minimum Value Maximum Value
int8_t signed char Signed 8 1 -128 127
uint8_t unsigned char Unsigned 8 1 0 255
int16_t short Signed 16 2 -32,768 32,767
uint16_t unsigned short Unsigned 16 2 0 65,535
int32_t int Signed 32 4 -2,147,483,648 2,147,483,647
uint32_t unsigned int Unsigned 32 4 0 4,294,967,295
int64_t long long Signed 64 8 -9,223,372,036,854,775,808 9,223,372,036,854,775,807
uint64_t unsigned long long Unsigned 64 8 0 18,446,744,073,709,551,615
### size_t与ssize_t

size_t主要用于计数,如sizeof函数返回值类型即为size_t。在不同位的机器中所占的位数也不同,size_t是无符号数,ssize_t是有符号数。

  1. 在32位机器中定义为:typedef unsigned int size_t; (4个字节)
  2. 在64位机器中定义为:typedef unsigned long size_t;(8个字节)

由于size_t是无符号数,因此,当变量有可能为负数时,必须使用ssize_t。因为当有符号整型和无符号整型进行运算时,有符号整型会先自动转化成无符号。

int main()
{
    unsigned short a;
    short int b = -1;
    a = b;
    cout << "b=" << b << endl;  //b=-1
    cout << "a=" << a << endl;  //a=65535
}

此外,int 无论在32位还是64位机器中,都是4个字节, 且带符号,可见size_t与int 的区别之处。

你可能感兴趣的:(C/C++,c语言)