问题描述
我注意到现代 C 和 C++ 代码似乎在几乎所有地方都使用 size_t
而不是 int
/unsigned int
- 从 C 的参数字符串函数到 STL.我很好奇这样做的原因及其带来的好处.
I notice that modern C and C++ code seems to use size_t
instead of int
/unsigned int
pretty much everywhere - from parameters for C string functions to the STL. I am curious as to the reason for this and the benefits it brings.
推荐答案
size_t
类型是无符号整数类型,它是 sizeof
运算符(和offsetof
运算符),因此它保证足够大以包含系统可以处理的最大对象的大小(例如,8Gb 的静态数组).
The size_t
type is the unsigned integer type that is the result of the sizeof
operator (and the offsetof
operator), so it is guaranteed to be big enough to contain the size of the biggest object your system can handle (e.g., a static array of 8Gb).
size_t
类型可能大于、等于或小于 unsigned int
,并且您的编译器可能会对其进行假设以进行优化.
The size_t
type may be bigger than, equal to, or smaller than an unsigned int
, and your compiler might make assumptions about it for optimization.
您可以在 C99 标准第 7.17 节中找到更准确的信息,其草案可在 Internet 上的 pdf 格式,或在 C11 标准第 7.19 节中,也可作为 pdf 草稿.
You may find more precise information in the C99 standard, section 7.17, a draft of which is available on the Internet in pdf format, or in the C11 standard, section 7.19, also available as a pdf draft.
这篇关于unsigned int 与 size_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!