user695652 user695652 - 1 year ago 60
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
, thus vec.size() -1 evaluates to
on my system.

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download