问题
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