Glibc的设计确实巧妙的让人想不到,如下strcmp的代码就十分巧妙:
C语言: Codee#12462
int
strcmp (p1, p2)
const char p1;
const char p2;
{
register const unsigned char s1 = (const unsigned char ) p1;
register const unsigned char s2 = (const unsigned char ) p2;
unsigned reg_char c1, c2;
do
{
c1 = (unsigned char) s1++;
c2 = (unsigned char) s2++;
if (c1 == \'\\0\')
return c1 - c2;
}
while (c1 == c2);
return c1 - c2;
}
它使用了寄存器变量就会很快了,又只是用了两个判断来确定循环是否继续,这才是程序的关键!因为如果c2==\’\0\’的话,那么c1有两种情况,第一c1不等于\’\0\’,这种情况下那就会不满足c1 == c2 这个条件,退出循环;然而如果c1也等于\’\0\’的话,那么程序满足c1 == \’\0\’的条件,那退出程序。