ccastingintegersize-t

Can I compare int with size_t directly in C?


Can I compare an int and a size_t variable like this:

int i = 1;
size_t y = 2;
if (i == y) {
    // Do something
}

Or do I have to type cast one of them?


Solution

  • 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)