达夫设备(duff's device)

达夫设备(Duff’s device)是 c 编程语言里将循环展开的编程技巧。
具体就是使用 switch 和 loop 结合,将 case 写在 loop 里面。
下面代码展示里其执行过程:

#include 
#include 
#include 

void copy(int src[], int dest[], int size) {
    int rounds = size / 8;

    int i = 0;
    switch (size % 8)
    {
    case 0:
        while (!(rounds == 0))
        {
            rounds = rounds - 1;
            dest[i] = src[i];
            i = i + 1;

        case 7:
            dest[i] = src[i];
            i = i + 1;
        case 6:
            dest[i] = src[i];
            i = i + 1;
        case 5:
            dest[i] = src[i];
            i = i + 1;
        case 4:
            dest[i] = src[i];
            i = i + 1;
        case 3:
            dest[i] = src[i];
            i = i + 1;
        case 2:
            dest[i] = src[i];
            i = i + 1;
        case 1:
            dest[i] = src[i];
            i = i + 1;
        };
    }
}

int main () {
        int size = 20;
        int dest[size], src[size];

        // Assign some random values to src[] 
        int i;
        for (i=0; i<size; i++)
                src[i] = rand()%2;

        copy(src, dest, size);

        for (i=0; i<size ; i++)
                printf("%d\t%d\n", src[i], dest[i]);
}

注意while 循环里的 case 语句后 面没有 break,所以while循环里的case语句会顺序依次执行。

你可能感兴趣的:(C)