difference between i + 1 < vec.size() and i < vec.size() - 1

Viewed 362

while programming I found out that my code was giving runtime error when I was using condition i < vec.size() - 1 but was working fine for i + 1< vec.size(). here vec was an empty std::vector.

//giving error
vector<int> vec;
for (int i = 0; i < vec.size() - 1; i++)
{
    //some code
}
//not giving error
vector<int> vec;
for (int i = 0; i + 1 < vec.size(); i++)
{
    //some code
}
2 Answers

The method std::vector::size returns a std::size_t which is unsigned. So if it is empty, you will get 0 - 1, but represented as an unsigned number, that will underflow and become 18446744073709551615 according to two's complement.

Sidenote. It's not a good idea to compare signed and unsigned numbers. In C++20 we will have a new function std::ssize that returns a signed type. Then your example written as

 for (std::ptrdiff_t i = 0; i < std::ssize(vec) - 1; ++i)
 {
     //some code
 }

will be perfectly valid.

Note also how i is declared to be an std::ptrdiff_t (a signed integer type) to indicate array indexing.

Related