1

The std::array template parameters are template < class T, size_t N > class array; where N stands for the number of elements in the array.

My doubt is why is the type std::size_t? Isn't std::size_t an alias for the size of an object/pointer in bytes. std::size_t

Why is it used to denote the number of elements in std::array here?

Jash Jain
  • 119
  • 6
  • It is also the default size and index type for pretty much every container and algorithm in the standard library. The notable exception being to represent the distance between elements, where the value can be negative. – François Andrieux Aug 04 '20 at 17:40
  • Note that the term "object" is kind of overloaded in C++. Sure you have the OOP terminology floating around, but in [C++ just about everything is an object](https://en.cppreference.com/w/cpp/language/object). It is literally easier to list what isn't an object than what is. – user4581301 Aug 04 '20 at 17:52
  • Sorry I'm a new user, thank you for pointing that out David, I've made the changes – Jash Jain Aug 04 '20 at 18:06

1 Answers1

5

The type std::size_t is defined to be a numeric type that can represent the size of the largest possible object (say, N bytes).

The largest object could be an array, and the array with the most possible objects is therefore an array of N chars.

So, std::size_t makes sense for array indexes and dimensions too.

You should stick to this convention as much as possible, because otherwise you potentially introduce bugs:

std::size_t is commonly used for array indexing and loop counting. Programs that use other types, such as unsigned int, for array indexing may fail on, e.g. 64-bit systems when the index exceeds UINT_MAX or if it relies on 32-bit modular arithmetic (cppref)

We could have had a std::index_t instead, but it would have been the same as std::size_t, so that's pointless.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35