总之,用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
本文探讨了size_t和ptrdiff_t在C/C++中的应用,包括它们的定义、使用场景及注意事项。通过代码示例展示了如何正确使用这些类型来提高程序的可移植性和效率。
1684

被折叠的 条评论
为什么被折叠?



