As we have seen in std::vector length and indexing note, type of indices are of size_type which is an unsigned integral type. As we know that working with unsigned integral type is an issue because of their unexpected behavior when they go out of their range (explain in type conversion).
Note
If index is a constexpr, then using it should not be a problem because compile would make sure it is always positive. For example,
constexpr int index{0};array[index]; // not an issueconstexpr int index{-1};array[index]; // compiler gives warningint index{0};array[index]; // compiler gives warning as index may get nagative.
And thus using them in loops for indexing will limit us using it as the ending conditional. For example,
for (std::size_t index{array.size() - 1}; index >= 0; --index){ // statements}
What do you think how many times the loop should execute, if array.size() results in 5? 5 times? The answer is the loop will never get terminated. This is because when index (of unsigned type) reaches 0 and --index happens, we would expect it to become -1, but as it is unsigned, it gets modulo wrapped to any non-negative value as unsigned integral can’t store negative value. So, index would always be positive and loop will never terminate.
Furthermore, using this index value which gets larger than the array size itself, would result index out of bound error.
This is one issue.
Second issue is when we try to cover this problem. We convert index value to signed integral and then again convert to unsigned int when indexing the array.
for (std::ptrdiff_t static_cast<std::ptrdiff_t>(index{array.size() - 1}); index >= 0; --index){ std::cout << array[static_cast<std::size_t>(index)] << "\n";}
This makes accessing the array very hard and code becomes cluttered.
So, unless and required, we should look for options where we could say away from accessing array using indexes. We could use range based for loop as an option.