According to cpprefernece size_t
is defined in various headers, namely
cstddef , cstdio, cstdlib, cstring, ctime, cuchar and (since C 17) cwchar.
My question is why is there not a single definition of size_t
? Which header do I include, if I just want size_t
?
CodePudding user response:
My question is why is there not a single definition of size_t?
There is a single definition for std::size_t
. It's just defined in multiple headers since those headers themselves use that definition.
Which header do I include, if I just want size_t?
Any of the ones that are specified to define it.
My choice is typically, <cstddef>
because it is very small and has other definitions that I'm likely to need such as std::byte
.
CodePudding user response:
Generally any standard library header may introduce any of the other header's declarations into the std
namespace, but the declarations will always refer to the same entity and there won't be any one-definition-rule violation or anything like that. The headers listed on cppreference are just the ones for which a guarantee is made that they introduce std::size_t
.
<cstddef>
is probably the most minimal out of the headers and will also be available in a freestanding environment.
Note however, that none of the listed headers is guaranteed to introduce size_t
into the global namespace scope. If you require this, you need to include one of the C versions of the headers, e.g. #include<stddef.h>
.