schorsch312
schorsch312

Reputation: 5694

Which header to include for size_t

According to cpprefernece size_tis 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?

Upvotes: 1

Views: 904

Answers (2)

user17732522
user17732522

Reputation: 76678

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>.

Upvotes: 1

eerorika
eerorika

Reputation: 238341

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.

Upvotes: 4

Related Questions