Difference between size_t and unsigned int?

后端 未结 7 1061
清酒与你
清酒与你 2020-11-28 01:29

I am so confused about size_t. I have searched on the internet and everywhere mentioned that size_t is an unsigned type so, it can represent only n

7条回答
  •  爱一瞬间的悲伤
    2020-11-28 02:07

    There are 5 standard unsigned integer types in C:

    • unsigned char
    • unsigned short
    • unsigned int
    • unsigned long
    • unsigned long long

    with various requirements for their sizes and ranges (briefly, each type's range is a subset of the next type's range, but some of them may have the same range).

    size_t is a typedef (i.e., an alias) for some unsigned type, (probably one of the above but possibly an extended unsigned integer type, though that's unlikely). It's the type yielded by the sizeof operator.

    On one system, it might make sense to use unsigned int to represent sizes; on another, it might make more sense to use unsigned long or unsigned long long. (size_t is unlikely to be either unsigned char or unsigned short, but that's permitted).

    The purpose of size_t is to relieve the programmer from having to worry about which of the predefined types is used to represent sizes.

    Code that assumes sizeof yields an unsigned int would not be portable. Code that assumes it yields a size_t is more likely to be portable.

提交回复
热议问题