2012-06-20 12 views
1

我發現memcmp.c仿生是這樣的:爲什麼memcmp在仿生中是這樣的?

30 int memcmp(const void *s1, const void *s2, size_t n) 
31 { 
32  const unsigned char* p1 = s1; 
33  const unsigned char* end1 = p1 + n; 
34  const unsigned char* p2 = s2; 
35  int     d = 0; 
36 
37  for (;;) { 
38   if (d || p1 >= end1) break; 
39   d = (int)*p1++ - (int)*p2++; 
40 
41   if (d || p1 >= end1) break; 
42   d = (int)*p1++ - (int)*p2++; 
43 
44   if (d || p1 >= end1) break; 
45   d = (int)*p1++ - (int)*p2++; 
46 
47   if (d || p1 >= end1) break; 
48   d = (int)*p1++ - (int)*p2++; 
49  } 
50  return d; 
51 } 

在for循環中,同樣的邏輯重複4次,爲什麼呢?它可以不重複嗎?

THX, 維克多

回答

2

這是一個手動循環展開。它可以只做一次,或者甚至用一個規則的循環而不是無限循環,它也可以做4次以上。有人認爲這給了編譯器更好的機會來優化生成的代碼。

欲瞭解更多信息,請檢查http://en.wikipedia.org/wiki/Loop_unrolling

+0

太棒了!謝謝你的迴應,你給我一個大手,謝謝! –