Mashakal Mashakal - 3 months ago 18
C Question

comparing off_t and ssize_t with other types

I am new to C and recently ran into some trouble with mismatching data types and their memory allocation. I am writing a very simple program to calculate the xor checksum of a file read using Linux system calls.

My question is this: Do I need to be concerned with unpredictable results when comparing an off_t or ssize_t with a long or int?

For example:

long i;
for(i = 0; i < fileStat.st_size; i++)
{
// do stuff
}


and also:

ssize_t i;
for(i = 0; i < fileStat.st_size; i++)
{
// do stuff
}

Answer

Comparing types of the same signedness but different size with one-another works, as the smaller type is extended to the larger type. Comparing types of different signedness is problematic as you could get wrong results if the signed type is not larger than the unsigned type and the signed number is negative. It is a good idea to make sure the signed number is not negative at first:

signed_t a;
unsigned_t b;

/* instead of */
if (a < b)
    /* ... */

/* use */
if (a < 0 || a < b)
    /* ... */