Can I compare int with size_t directly in C?

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)

Leave a Comment