总之,用size_t 保证可移植性,保证其可以表示出最大需要表示的长度。
size_t 在stddef.h 中无命名空间
在<cstddef>有std::
size_t 与ptrdiff_t 要联合使用
When i
is signed and size
is unsigned, then i
is converted to unsigned before the comparison is performed. This is part of what are called the usual arithmetic conversions.http://stackoverflow.com/questions/4311538/strange-behaviour-with-for-loop-and-size-t
unsigned int vs. size_t:
When to use std::size_t?
Difference between size_t and std::size_t
(ptrdiff_t 在64位下有更高的效率)
#include <iostream>
#include <stddef.h>
template <typename T, int N>
int size(T (&)[N])
{
return N;
}
int main()
{
int a[20];
std::cout<<size(a)<<std::endl;
std::cout<<"sizeof(short):"<<sizeof(short)<<std::endl;
std::cout<<"sizeof(float):"<<sizeof(float)<<std::endl;
std::cout<<"sizeof(double):"<<sizeof(double)<<std::endl;
std::cout<<"sizeof(long):"<<sizeof(long)<<std::endl;
std::cout<<"sizeof(size_t):"<<sizeof(size_t)<<std::endl;
std::cout<<"sizeof(ptrdiff_t):"<<sizeof(ptrdiff_t)<<std::endl; // error when not using #include <stddef.h>
std::cout<<"sizeof(ptrdiff_t):"<<sizeof(std::ptrdiff_t)<<std::endl;
return 0;
}
结果:
sizeof(short):2
sizeof(float):4
sizeof(double):8
sizeof(long):8
sizeof(size_t):8
sizeof(ptrdiff_t):8
sizeof(ptrdiff_t):8