看到一段代码,学习一下:
1 void* mymemcpy( void* dest, const void* src, size_t count )
2 {
3 char* d = (char*)dest;
4 const char* s = (const char*)src;
5 int n = count>>3;
6 switch( count & 7 )
7 {
8 case 0:
9 do {
10 *d++ = *s++;
11 case 7: *d++ = *s++;
12 case 6: *d++ = *s++;
13 case 5: *d++ = *s++;
14 case 4: *d++ = *s++;
15 case 3: *d++ = *s++;
16 case 2: *d++ = *s++;
17 case 1: *d++ = *s++;
18 } while (--n > 0);
19 }
20 return dest;
21 }
实际上也可以这么写
1 void* mymemcpy( void* dest, const void* src, size_t count )
2 {
3 char* d = (char*)dest;
4 const char* s = (const char*)src;
5 // int n = (count + 7) / 8; // count > 0 assumed
6 int n = count >> 3;
7 switch( count & 7 )
8 {
9 do { *d++ = *s++;
10 case 7: *d++ = *s++;
11 case 6: *d++ = *s++;
12 case 5: *d++ = *s++;
13 case 4: *d++ = *s++;
14 case 3: *d++ = *s++;
15 case 2: *d++ = *s++;
16 case 1: *d++ = *s++;
17 case 0 } //while (--n > 0);
18 while (n-- > 0)
19 }
20
21 return dest;
22 }
23
24
这么写更容易理解
实际上这里也可以是4个字节来复制,而不是8。其实这个看喜好。