程序很短,程序的思路和我们平常写的是一样的,即找到前面串的结尾,然后将后面的串接上,但是有些地方是经过了优化的,值得我们去学习。
优化点1:中间变量使用寄存器变量,提高了程序运行效率。
优化点2:最后一个循环巧妙地将最后的’\0’赋值给了合并串的尾部,不需要额外的语句再去管理最后的’\0’。
下面是加入了我思考的代码(英文部分是原作者的注释):
#include <string.h>
#include <memcopy.h>
#undef strcat
/* Append SRC on the end of DEST. */
char *
strcat (dest, src)
char *dest;
const char *src;
{
//新定义两个临时指针用于操作
char *s1 = dest;
const char *s2 = src;
//定义一个寄存器变量,提高程序运行效率
reg_char c;
/* Find the end of the string. */
//找到前面字符串的串尾
do
c = *s1++;
while (c != '\0');
/* Make S1 point before the next character, so we can increment
it while memory is read (wins on pipelined cpus). */
//此时s1指向前面字符串的串尾的后一个位置,减2的话就是指向前面字
//符串的最后一个字符
s1 -= 2;
//结束循环后合并的字符串后面的'\0'已经做了赋值,因此调用strcat后
//不需要再次手动添加'\0'
do
{
c = *s2++;
*++s1 = c;
}
while (c != '\0');
return dest;
}
libc_hidden_builtin_def (strcat)
注:glibc版本为2.9。