comparing int with size_t

It's safe provided the int is zero or positive. If it's negative, and size_t is of equal or higher rank than int, then the int will be converted to size_t and so its negative value will instead become a positive value. This new positive value is then compared to the size_t value, which may (in a staggeringly unlikely coincidence) give a false positive. To be truly safe (and perhaps overcautious) check that the int is nonnegative first:

/* given int i; size_t s; */
if (i>=0 && i == s)

and to suppress compiler warnings:

if (i>=0 && (size_t)i == s)

size_t is going to be some sort of integer type (although possibly unsigned, so it might generate a warning) so the appropriate casting should be done for you automatically.

As others have already said, you may want to revisit whatever calculation is producing the int and see if you can do it in size_t in the first place if you're computing a required size for something.


If you're going to compare an int type to size_t(or any other library type), you are doing a risky comparison because int is signed and size_t is unsigned, so one of them will be implicitly converted depending on your compiler/platform. The best thing to do, is to rewrite your int i as:

decltype(y.size()) i = 1;

This assigns your i as the safe type you're trying to compare, and I think it's good practice. This solution is useful in all types of iterators as well. You generally don't want to trust the compiler to cast for you, you can, but it's risky, and an unnecessary risk.

Tags:

C

Casting