Jash Jain
Jash Jain

Reputation: 139

size_t template parameter in std::array

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?

Upvotes: 1

Views: 428

Answers (1)

Asteroids With Wings
Asteroids With Wings

Reputation: 17454

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.

Upvotes: 5

Related Questions