user695652 user695652 - 3 days ago 5
C++ Question

subtraction from size_t results in large positive number

I just run into a nasty bug where I have a loop

for (auto i = 0; i < vec.size() -1; ++i) {
//
}


with vec being an emtpy
std::vector
, thus vec.size() -1 evaluates to
2^64
on my system.

What's the correct way of writing the above loop?

Answer

size_t is an unsigned type hence the problem, just do that this way:

for (auto i = 0U; i + 1 < vec.size(); ++i) 

0U added to make i unsigned (to avoid warning), but I would better use size_t istead of auto in this case

Comments