在32位和64位系统的strcmp行为 [英] strcmp behaviour in 32-bit and 64-bit systems

查看:354
本文介绍了在32位和64位系统的strcmp行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code的一块表现不同的32位和64位操作系统。

The following piece of code behaves differently in 32-bit and 64-bit operating systems.

char *cat = "v,a";
if (strcmp(cat, ",") == 1)
    ...

以上的条件是在32位的事实,但在64位假的。我不知道这是为什么不同?
32位和64位操作系统Linux的是(Fedora的)。

The above condition is true in 32-bit but false in 64-bit. I wonder why this is different? Both 32-bit and 64-bit OS are Linux (Fedora).

推荐答案

的strcmp()函数只被定义为返回一个负值,如果参数1 precedes说法2,零如果他们是相同的,或正值如果参数1所示参数2

The strcmp() function is only defined to return a negative value if argument 1 precedes argument 2, zero if they're identical, or a positive value if argument 1 follows argument 2.

有在任何时候任何任何形式返回的值将是 +1 1 的保证。基于上述假设的任何相等测试故障。可以想象的是, STRCMP的32位和64位版本()对于给定的字符串比较返回不同的数字,但是这看起来对于 +1 从的strcmp()本质上是有缺陷的。

There is no guarantee of any sort that the value returned will be +1 or -1 at any time. Any equality test based on that assumption is faulty. It is conceivable that the 32-bit and 64-bit versions of strcmp() return different numbers for a given string comparison, but any test that looks for +1 from strcmp() is inherently flawed.

您比较code应该之一:

Your comparison code should be one of:

if (strcmp(cat, ",") >  0)    // cat >  ","
if (strcmp(cat, ",") == 0)    // cat == ","
if (strcmp(cat, ",") >= 0)    // cat >= ","
if (strcmp(cat, ",") <= 0)    // cat <= ","
if (strcmp(cat, ",") <  0)    // cat <  ","
if (strcmp(cat, ",") != 0)    // cat != ","

请注意共同的主题 - 所有的测试与对比0您还可以看到人写的:

Note the common theme — all the tests compare with 0. You'll also see people write:

if (strcmp(cat, ","))   // != 0
if (!strcmp(cat, ","))  // == 0

我个人preFER零明确的比较;我精神上翻译速记到适当的手写(和痛恨做这样的)。

Personally, I prefer the explicit comparisons with zero; I mentally translate the shorthands into the appropriate longhand (and resent being made to do so).

注意 的strcmp()<的规格/ code> 说:

¶3的的strcmp 函数返回大于的整数,等于,或小于零,
  因此作为字符串指向 S1 大于,等于或小于字符串指向 S2

ISO/IEC 9899:2011 §7.24.4.2 The strcmp function

¶3 The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

据只字未提 +1 1 ;你可以不依赖于结果的大小,只在它的符号性(或者说是零,当字符串相等)。

It says nothing about +1 or -1; you cannot rely on the magnitude of the result, only on its signedness (or that it is zero when the strings are equal).

这篇关于在32位和64位系统的strcmp行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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