小于比。平等,要以提高效率C / C ++ [英] Less-Than Vs. Equal-To For Efficiency C/C++

查看:85
本文介绍了小于比。平等,要以提高效率C / C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我用旧的的API,例如,在Unix上的C套接字API,我总是看到人们青睐小于(< )在equal-到( == )比较其错误的返回值时。

When I've used older APIs, for example, the C sockets API on Unix, I always notice that people favor less-than (<) over equal-to (==) when comparing their bad return values.

int result = send(...);
if (result < 0) { perror("..."); }

在我指的情况下,返回code是只有永远积极, 0 1 (用错误号设置为正确的值)。那么,为什么不只是检查错误使用(结果== -1)而不是(导致℃下)

In the cases I'm referring to, the return code is only ever positive, 0, or -1 (with errno set to the right value). So why not just check for an error using (result == -1) instead of (result < 0)?

我这么问是因为我,如果它这样做是出于习惯,或想知道,如果它是更有效地使用小于?我在想的是,如果你比较两个 uint64_t中和你发现在MSB的差异,您就不必检查其他7个字节,等等。我可能会与此逻辑来达到,但!

I'm asking because I was wondering if it's done out of habit or if it's more efficient to use less-than? I was thinking about the fact that if you were comparing two uint64_ts and you found the difference in the MSB, you wouldn't have to check the other 7 bytes, etc. I might be reaching with this logic though!

推荐答案

我认为这是既不习惯也不是效率。因为你不依赖于特定的收益code是比较安全的。相反,你靠的错误code为负。例如,的strcmp 函数返回负值当第一串比第二小。在大多数的实现,它将返回 1 ,但要处理它的正确方法是检查&LT; 0

I think that this is neither for habit nor for efficiency. It is safer because you don't rely on a specific return code. Instead, you rely for the error code to be negative. For instance, strcmp function returns "a negative value" when the first string is smaller than the second. On most implementations, it will return -1, but the correct way to handle it is to check for < 0

这篇关于小于比。平等,要以提高效率C / C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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