Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

c - 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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
    /* ... */

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...