优化的 strcmp 实现 [英] Optimized strcmp implementation

查看:55
本文介绍了优化的 strcmp 实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处找到此函数.它是 strcmp 的一个实现:

This function was found here. It's an implementation of strcmp:

int strcmp(const char* s1, const char* s2)
{
    while (*s1 && (*s1 == *s2))
        s1++, s2++;
    return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}

除了最后一行我都明白了,总之最后一行是怎么回事?

I understand all but the last line, in short what is going on in the last line?

推荐答案

return *(const unsigned char*)s1-*(const unsigned char*)s2;

OP:简而言之,最后一行发生了什么?

OP: in short what is going on in the last line?

A:比较第一个潜在的字符串差异.根据规范的要求,两个 chars 都被引用为 unsigned char.2 被提升为 int 并返回差异.

A: The first potential string difference is compared. Both chars are referenced as unsigned char as required by the spec. The 2 are promoted to int and the difference is returned.

注意事项:

1 返回值的符号 (<0, 0, >0) 是最有意义的部分.它是 C 规范中唯一指定的部分.

1 The return value's sign (<0, 0, >0) is the most meaningful part. It is the only part that is specified by the C spec.

2 在某些系统上,charsigned(更常见).在其他情况下,charunsigned.定义最后一个比较的符号"可以提高可移植性.请注意,fgetc() 获取字符为 unsigned char.

2 On some systems char is signed (more common). On others, char is unsigned. Defining the "sign-ness" of the last comparison promotes portability. Note that fgetc() obtains characters as unsigned char.

3 除了字符串以 \0 结尾之外,所采用的字符编码(如 ASCII - 最常见)在二进制级别没有区别.如果两个字符串中第一个 char 的值分别为 65 和 97,则第一个字符串将小于第二个,即使字符编码是非 ASCII.OTOH,strcmp("A", "a") 当字符编码为 ASCII 时将返回负数,但可能会返回不同字符编码中的正数,因为它们的底层值和顺序未定义由 C.

3 Other than that a string ends with a \0, the character encoding employed (like ASCII - most common), makes no difference at the binary level. If the first chars that differ in 2 strings have values 65 and 97, the first string will be less than the second, even if the character encoding is non-ASCII. OTOH, strcmp("A", "a") will return a negative number when character encoding is ASCII, but may return a positive number in a different character encoding for their underlying value and order are not defined by C.

这篇关于优化的 strcmp 实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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