Suppose we start with:
void Procedure (unsigned int Len) { int i; for (i = 0; i < Len; i++) { InnerLoop (i); } } When unrolling loops, one is typically trying to reduce loop overhead (incrementing and branching.) K & R were vague in their definition of the "switch" statement and left it open to the following usage: void Procedure (unsigned int Len) { int i; if (Len == 0) return; i = ((Len - 1) & 7) - 7; switch (-i) { do { case 0: InnerLoop (i + 0); case 1: InnerLoop (i + 1); case 2: InnerLoop (i + 2); case 3: InnerLoop (i + 3); case 4: InnerLoop (i + 4); case 5: InnerLoop (i + 5); case 6: InnerLoop (i + 6); case 7: InnerLoop (i + 7); i += 8; } while (i < Len); } } And when they (K & R) were asked about this, they said that this in fact was one of the intended uses of the switch statement. The ANSI standard also has no beef with it, and neither do most modern C compilers. This technique is commonly known as "Duff's device". |