c - 理解gnu libc的strcmp函数

标签 c linux glibc strcmp

这是 strcmp我在 glibc 中找到的函数:

int
STRCMP (const char *p1, const char *p2)
{
  const unsigned char *s1 = (const unsigned char *) p1;
  const unsigned char *s2 = (const unsigned char *) p2;
  unsigned char c1, c2;

  do
    {
      c1 = (unsigned char) *s1++;
      c2 = (unsigned char) *s2++;
      if (c1 == '\0')
        return c1 - c2;
    }
  while (c1 == c2);

  return c1 - c2;
}

这是一个非常简单的函数,其中 while 的主体同修c1c2值为 *s1*s2并继续直到 c1nulc1 的值和 c2相等,然后返回 c1 之间的差值和 c2 .

我不明白的是s1的用法和 s2变量。我的意思是除了它们是 unsigned char 之外的事实他们也是const像 2 个参数 p1p2 , 那么为什么不直接使用 p1p2在体内同时施放它们?在这种情况下,使用这两个额外变量是否会使函数以某种方式更加优化?因为这是我在 github 上找到的适用于 FreeBSD 的相同功能:

int
strcmp(const char *s1, const char *s2)
{
    while (*s1 == *s2++)
        if (*s1++ == '\0')
            return (0);
    return (*(const unsigned char *)s1 - *(const unsigned char *)(s2 - 1));
}

在他们的版本中,他们甚至懒得使用任何额外的变量。

预先感谢您的回答。

PS:我在这里问之前确实在互联网上搜索过这个具体事实,但我没有得到任何东西。

我也想知道glibc是否有任何特殊原因使用那些额外的变量而不是强制转换参数 p1p2直接在里面while .

最佳答案

What i didn't understand is the use of s1 and s2 variables. I mean other than the fact that they are unsigned char they are also const like the 2 arguments p1 and p2, so why not just use the p1 and p2 inside the body of while and cast them ?

为了可读性;让我们人类更容易维护代码。

如果你看glibc的源码,代码更倾向于可读性而不是简洁的表达。这似乎是一项很好的政策,因为 30 多年来它一直保持相关性和活力(积极维护)。

Does in this case using those 2 extra variables make the function somehow more optimized?

不,一点也不。

I would also like to know if there are any particular reason why glibc used those extra variables instead of casting the parameters p1 and p2 directly inside while.

仅供阅读。

作者知道使用的C编译器应该能够很好地优化这段代码。 (并且很容易证明是这种情况,只需查看编译器生成的代码。对于 GCC,您可以使用 -S 选项,或者您可以使用 binutils 的 objdump -d 检查目标文件或二进制可执行文件。)

请注意,出于与 isspace() 完全相同的原因,需要强制转换为 unsigned char , isalpha() 等等:比较的字符代码必须被视为 unsigned char 才能获得正确的结果。

关于c - 理解gnu libc的strcmp函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53039818/

相关文章:

linux - 使用 gcc 时找不到版本 `GLIBC_2.11'

c - unix 中 exec() 和 system() 的区别

c - 未知的段错误

c - 具有多个定义的不透明结构

linux - 驱动程序编程 : cat command not showing output

用于显示用于引导/根分区的文件系统名称的 Linux 命令

matlab - 在 centOS 中选择 Glibc 版本

c - C中的IPv6地址复制优化

c - 在图中删除/插入顶点时出现问题

linux - 须藤:找不到命令