Is size_t large enough to represent size of any type? [duplicate]

邮差的信 提交于 2021-02-08 14:59:01

问题


Is size_t guaranteed to be large enough to represent size of any type? According to this reference:

size_t can store the maximum size of a theoretically possible object of any type (including array).

This is generally a reliable reference but I could not find anything proving or disputing this claim in the relevant parts of the standard.


回答1:


Yes. size_t is defined in stddef.h, according to the C99 standard in the section on the sizeof operator (6.5.3.4):

The value of the result is implementation-defined, and its type (an unsigned integer type) is size_t, defined in <stddef.h> (and other headers).

Since

The sizeof operator yields the size (in bytes) of its operand

and its return type is size_t, size_t must be able to contain the size of any type.




回答2:


Per the C11 standard, 6.5.3.4 The sizeof and _Alignof operators, paragraph 2:

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. ...

Thus, sizeof can be used to get the size of any object.

Per paragraph 5:

The value of the result of both operators is implementation-defined, and its type (an unsigned integer type) is size_t, defined in <stddef.h> (and other headers).

and size_t can hold the result of getting the size of any object.

Ergo, size_t can hold the size of any object.



来源:https://stackoverflow.com/questions/57827073/is-size-t-large-enough-to-represent-size-of-any-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!