Help ensure/confirm type of..

The type of array index is std::size_t isn't?
Last edited on
there is no such thing as an array index type.
size_t is unsigned, and negative array indexing is both possible and legal, so generally speaking the array index is usually some flavor of integer.

an example of negative indexing:
int lookup[] {-0.001,-0.01,-0.1, 1,10,100,1000};
int *lookie = &lookup[3];
cout << "10 to the -2 is: " << lookie[-2];

that said, for normal indexing, size_t is fine.
Last edited on
For the built-in subscript operator the standard says you have to use an enum or integer type.

https://eel.is/c++draft/expr.sub

For std::array the subscript operator takes an index of type std::size_t.

For std::vector it's technically "implementation defined". It's usually std::size_t. Even if it's not it's still fine to use std::size_t.
Last edited on
Note that if you have an index of type int and are comparing it's value to .size() or std::size() then the compiler will likely warn about unsigned/signed mismatch and the range may not be large enough as for 64-bit compile size_t is 64 bits but int could be 32 bits.

If you want a signed index, then use ptrdiff_t which is a signed type and if needed compare it to std::ssize() (also signed - since C++20). Both ptrdiff_t and std::ssize() adjust correctly for 32/64 bit compiles.
Topic archived. No new replies allowed.