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

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

问题描述

以下代码在 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 在参数 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 中查找 +1 的测试code>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.

您的比较代码应该是以下之一:

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

就个人而言,我更喜欢与零的显式比较;我在心理上将速记翻译成适当的速记(并且讨厌这样做).

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()的规范 说:

Note that the specification of strcmp() says:

¶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天全站免登陆