比较off_t和ssize_t供与其它类型的 [英] comparing off_t and ssize_t with other types

查看:251
本文介绍了比较off_t和ssize_t供与其它类型的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C,最近遇到了一些麻烦不匹配的数据类型和它们的内存分配。我写一个非常简单的程序来计算文件的异或校验使用Linux系统调用的读取。

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.

我的问题是:我需要比较的 off_t ssize_t供长或内部

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?

例如:

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

和也:

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


推荐答案

与-另一作品比较类型相同的符号性,但不同大小的,因为较小的类型扩展到更大的类型。比较类型不同符号性是有问题的,你可以得到错误的结果,如果有符号的类型不大于无符号类型较大和符号数是负的。这是一个好主意,以确保签名的数字是不是负面的第一次:

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

这篇关于比较off_t和ssize_t供与其它类型的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆