1

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?

schorsch312
  • 5,553
  • 5
  • 28
  • 57
  • You can also `using size_t = decltype(sizeof 0);`, but my *go to* is `#include ` followed by `using std::size_t;`. – Eljay Mar 25 '22 at 14:20
  • @Eljay just don't do that in global namespace. – eerorika Mar 25 '22 at 14:22
  • @eerorika • should be okay to do in the global namespace. As an experiment, even okay to do before includes. Or multiple times. Or multiple times in different ways, e.g., `using size_t = decltype(sizeof 0); typedef unsigned long size_t;` (depending on the platform) if they all match. – Eljay Mar 25 '22 at 15:08
  • 1
    @Eljay Standard says that defining reserved names is UB. – eerorika Mar 25 '22 at 15:14
  • @eerorika • then that'd be bad. But is `::size_t` a reserved name? Of course `std::size_t` is reserved, because `std` namespace. And typedef'ing `::size_t` to anything other than what it ought to be will collide with almost any include file. I saw your answer here: https://stackoverflow.com/a/51500886/4641116 – Eljay Mar 25 '22 at 15:18
  • 2
    @Eljay It's reserved whether it's defined or not. Rule: `For each type T from the C standard library, the types ​::​T and std​::​T are reserved to the implementation and, when defined, ​::​T shall be identical to std​::​T.` – eerorika Mar 25 '22 at 15:42

2 Answers2

4

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

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

user17732522
  • 53,019
  • 2
  • 56
  • 105