c - 对于 q==p 的情况,为什么 memcmp 实现不使用快捷方式 memcmp(q, p, n) ?

标签 c glibc libc memcmp

如果我为 memcmp 的第一个和第二个参数传递相等的指针, 我怀疑它可能只是返回 0 而不检查元素——因为如果传递相同的指针,则元素必须为零。 在我看来,检查指针相等性并提前退出是很好的优化。

我检查了glibcFree BSD LibC 实现,并且似乎都没有进行这种优化。

所以我检查了标准(如下): Open Standards draft version of C99没有说任何一种方式或另一种方式:

7.21.4.1 The memcmp function Synopsis

#include <string.h>
int memcmp(const void *s1, const void *s2, size_t n);

Description

The memcmp function compares the first n characters of the object pointed to by s1 to the first n characters of the object pointed to by s2.

Returns

The memcmp function returns an inte ger greater than, equal to, or less than zero, accordingly as the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2

据我所知,它并不禁止这种“技巧”,因为人们仍然会得到相同的返回值。 这确实是一个实现细节,AFAICT。

显然,编写这些库的人比我对此投入了更多的思考,因此可能有充分的理由不这样做。 它是什么?

最佳答案

我怀疑这是出于实际实用性的考虑。

实际上,很少有人向 memcmp() 的第一个和第二个参数提供相同的指针。 ,因此在大多数情况下,额外条件测试没有任何有效作用,因此是浪费精力。

正如 Felix Palmen 在评论中指出的那样,如果可以静态确认两个指针指向同一地址,则编译器可以进行优化。

关于c - 对于 q==p 的情况,为什么 memcmp 实现不使用快捷方式 memcmp(q, p, n) ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50128370/

相关文章:

linux - 尝试引导 gcc/glibc 工具链

debian - 由于依赖关系损坏,apt-get 无法安装任何东西

python - IplImage 里面的 IplImage

objective-c - EXC_BAD_ACCESS,iphone 上的标准 c 库 "open"?

c - 非线程安全库和线程

rust - 更改Rust打印功能的默认文件描述符

c - 带有 malloc 的宏中的宏会导致运行时错误?

由整数键控并映射到空指针的 C 映射/哈希表

c - 为系统调用编写 glibc api

C:将数字转换为无区域设置的字符串的可移植/安全(线程感知)方法是什么?