glibc笔记——strlen
glib2.0中strlen函数的定义如下:
#include <string.h>
size_t
strlen (const char *str)
{
int cnt;
asm("cld\n" /* Search forward. 清方向位 */
/* Some old versions of gas need `repne' instead of `repnz'. */
//ECX!=0且ZF=0则继续循环
"repnz\n" /* Look for a zero byte. */
//AL-(ES:[EDI])
"scasb" /* %0, %1, %3 */ :
//输出cnt,初值为-1(==ECX);EAX=0;EDI=str
"=c" (cnt) : "D" (str), "0" (-1), "a" (0));
return -2 - cnt;
}
size_t
strlen (const char *str)
{
int cnt;
asm("cld\n" /* Search forward. 清方向位 */
/* Some old versions of gas need `repne' instead of `repnz'. */
//ECX!=0且ZF=0则继续循环
"repnz\n" /* Look for a zero byte. */
//AL-(ES:[EDI])
"scasb" /* %0, %1, %3 */ :
//输出cnt,初值为-1(==ECX);EAX=0;EDI=str
"=c" (cnt) : "D" (str), "0" (-1), "a" (0));
return -2 - cnt;
}
其中size_t的定义位于stddef.h:
typedef unsigned long size_t;
注意点:
(1)该函数返回无符号整数
if(strlen(x)>=strlen(y))...与
if(strlen(x)-strlen(y))...的含义并不相同,无符号数绝不可能为负数.
(2)一个自定义的实现:
#include <stdio.h>
size_t strlen(const char *str)
{
int len=0;
while(*str++!='\0')
len++;
return len;
}