能帮小弟我解释上strcmp源代码吗
能帮我解释下strcmp源代码吗?
int strcmp(const char *cs, const char *ct)
{
signed char __res;
while (1) {
if ((__res = *cs - *ct++) != 0 || !*cs++)
}
return __res;
}
尤其是if那句,能帮我解释一下,并分开写吗,分的越开越好,有注释最好。
比如m = *p++
分开写成 m = *p;
p++;
------解决方案--------------------
__res = *cs - *ct++
比较*cs和*ct的大小,然后ct指针往前走一步,不管谁大谁小,__res都会返回一个值,或正或负,或为0
(__res = *cs - *ct++) != 0
这个括号表达式的值等价于__res的值,就是说只有当__res不为0时(当前比较的字符大小不一样时,满足if条件前半句)
!*cs++
cs的值为0,则满足if后半句,然后cs指针前进一步
综上所述,if条件为真的情况是:当前比较的字符大小不一样,或者ct的值等于0,所以我猜测if后面应该是个break语句。
------解决方案--------------------
加了break也不对啊!
需要按照strcmp的返回值,需要按unsigned char来比较的
建议参考一下正确的代码
http://svnweb.freebsd.org/base/release/8.3.0/lib/libc/string/strcmp.c?view=markup
C89 关于strcmp的说明
4.11.4 Comparison functions
The sign of a nonzero value returned by the comparison functions is determined by the sign of the difference between the values of the first pair of characters (both interpreted as unsigned char ) that differ in the objects being compared.
4.11.4.2 The strcmp function
Synopsis
#include <string.h>
int strcmp(const char *s1, const char *s2);
Description
The strcmp function compares the string pointed to by s1 to the string pointed to by s2.
Returns
The strcmp function returns an integer greater than, equal to, or less than zero, according as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.
------解决方案--------------------
int strcmp(const char *cs, const char *ct)
{
signed char __res;
while (1) {
if ((__res = *cs - *ct++) != 0 || !*cs++)
}
return __res;
}
尤其是if那句,能帮我解释一下,并分开写吗,分的越开越好,有注释最好。
比如m = *p++
分开写成 m = *p;
p++;
------解决方案--------------------
__res = *cs - *ct++
比较*cs和*ct的大小,然后ct指针往前走一步,不管谁大谁小,__res都会返回一个值,或正或负,或为0
(__res = *cs - *ct++) != 0
这个括号表达式的值等价于__res的值,就是说只有当__res不为0时(当前比较的字符大小不一样时,满足if条件前半句)
!*cs++
cs的值为0,则满足if后半句,然后cs指针前进一步
综上所述,if条件为真的情况是:当前比较的字符大小不一样,或者ct的值等于0,所以我猜测if后面应该是个break语句。
------解决方案--------------------
加了break也不对啊!
需要按照strcmp的返回值,需要按unsigned char来比较的
建议参考一下正确的代码
http://svnweb.freebsd.org/base/release/8.3.0/lib/libc/string/strcmp.c?view=markup
C89 关于strcmp的说明
4.11.4 Comparison functions
The sign of a nonzero value returned by the comparison functions is determined by the sign of the difference between the values of the first pair of characters (both interpreted as unsigned char ) that differ in the objects being compared.
4.11.4.2 The strcmp function
Synopsis
#include <string.h>
int strcmp(const char *s1, const char *s2);
Description
The strcmp function compares the string pointed to by s1 to the string pointed to by s2.
Returns
The strcmp function returns an integer greater than, equal to, or less than zero, according as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.
------解决方案--------------------
int __cdecl strcmp (
const char * src,
const char * dst
)
{
int ret = 0 ;
while( ! (ret = *(unsigned char *)src - *(unsigned char *)dst) && *dst)
++src, ++dst;
if ( ret < 0 )
ret = -1 ;