0
template <typename T, std::size_t size>
void printArray(const std::array<T, size>& myArray)
{
    for (auto element : myArray)
        std::cout << element << ' ';
    std::cout << '\n';
}

Why is std::size_t being used? What are the benefits of size_t vs unsigned int?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • 7
    [`std::array`](https://en.cppreference.com/w/cpp/container/array) is defined with `std::size_t`, so it is natural to use the expected type in template... – Jarod42 Jun 03 '22 at 22:57
  • @bird_individual Sizes of objects is defined using the type size_t. The type unsigned int is unable to store all values that can be stored in an object of the type size_t. – Vlad from Moscow Jun 03 '22 at 23:01
  • 1
    And [`std:size_t`](https://en.cppreference.com/w/cpp/types/size_t) is the result type of `sizeof` operator. It may be bigger (and commonly is on 64-bit systems) than `unsigned int`. Not that you often deal with arrays with 1e10 elements, but... – Yksisarvinen Jun 03 '22 at 23:02
  • 1
    Put simply - there is no benefit and there are potentially problems if a `std::array`'s size is represented by an `unsigned int` in some places and a `size_t` in other places. – Drew Dormann Jun 03 '22 at 23:07
  • Well, as a general rule you shouldn’t be using type specifiers like `long x` and `unsigned x` if you can avoid it, which you can. C++ has a range of specific size types available in signed and unsigned versions. of which is `size_t` and `ssize_t` exist. – Taekahn Jun 03 '22 at 23:14
  • @Taekahn — `size_t` and `ssize_t` have implementation-specific sizes, just like `long` and `unsigned`. – Pete Becker Jun 03 '22 at 23:48
  • I wouldn’t say “just like”. Just because two thing are similar doesn’t make them equal. Modifiers like `long` have a lot more variance to it than size_t does. – Taekahn Jun 03 '22 at 23:57
  • 1
    Does this answer your question? [C++ - should you size\_t with a regular array?](https://stackoverflow.com/questions/32021860/c-should-you-size-t-with-a-regular-array) or perhaps [Why size_t is used for indexing / representing size of an array?](https://stackoverflow.com/questions/59728149/why-size-t-is-used-for-indexing-representing-size-of-an-array) – JaMiT Jun 04 '22 at 00:23
  • I frequently sort test arrays with >4 billion elements just because so many homework answers for `sort` fail that test. – Goswin von Brederlow Jun 04 '22 at 00:36

1 Answers1

0

std::size_t as its name clearly shows, is the standard type to store values for sizes of objects. It is the alaise of largest unsigned integer used by current standard(std::uint64_t) and can represent the largest possible virtual size. I don't find it practical to load a multi-GB file as a byte array in RAM; but if that's what must be done and the workstation can have a sufficiently large amount of RAM, then no other fundamental built-in type is capable of storing the size of resulting array or a proper index into it.

Red.Wave
  • 2,790
  • 11
  • 17