Is it better to cast the iterator condition right operand from size_t to int, or iterate potentially past the maximum value of int? Is the answer implementation specific?
int a;
for (size_t i = 0; i < vect.size(); i++)
{
if (some_func((int)i))
{
a = (int)i;
}
}
int a;
for (int i = 0; i < (int)vect.size(); i++)
{
if (some_func(i))
{
a = i;
}
}
I almost always use the first variation, because I find that about 80% of the time, I discover that
some_funcshould probably also take a size_t.If in fact
some_functakes a signed int, you need to be aware of what happens when vect gets bigger thanINT_MAX. If the solution isn’t obvious in your situation (it usually isn’t), you can at least replacesome_func((int)i)withsome_func(numeric_cast<int>(i))(see Boost.org for one implementation of numeric_cast). This has the virtue of throwing an exception when vect grows bigger than you’ve planned on, rather than silently wrapping around to negative values.