size_t 与 int 区别

(1)size_t和int
      size_t是一些C/C++标准在stddef.h中定义的。这个类型足以用来表示对象的大小。size_t的真实类型与操作系统有关。
在32位架构中被普遍定义为:

 typedef unsigned int     size_t;
    typedef int              ptrdiff_t;
    typedef int              intptr_t;

而在64位架构中被定义为:

typedef unsigned __int64 size_t;
    typedef __int64          ptrdiff_t;
    typedef __int64          intptr_t;


        size_t在32位架构上是4字节,在64位架构上是8字节,在不同架构上进行编译时需要注意这个问题。而int在不同架构下都是4字节,与size_t不同;且int为带符号数,size_t为无符号数,并且是平台有关的,表示0-MAXINT的范围。

(2)ssize_t

ssize_t是有符号整型,在32位机器上等同与int,在64位机器上等同与long int.

容易被坑的一些地方:

string str="123";
int a=2;
cout<<a-str.size()<<endl;
这段代码的输出并不是-1,在我64位win10系统中的输出是:4294967295,这是因为str.size()返回值是size_type一个无符号整数,而编译器在int与size_type做减法时,都视为了无符号整数。
 

猜你喜欢

转载自blog.csdn.net/qq_33263769/article/details/88739674