How does Duff's device work?

前端 未结 11 1677
日久生厌
日久生厌 2020-11-22 04:56

I\'ve read the article on Wikipedia on the Duff\'s device, and I don\'t get it. I am really interested, but I\'ve read the explanation there a couple of times and I still do

11条回答
  •  臣服心动
    2020-11-22 05:38

    Here's a non-detailed explanation which is what I feel to be the crux of Duff's device:

    The thing is, C is basically a nice facade for assembly language (PDP-7 assembly to be specific; if you studied that you would see how striking the similarities are). And, in assembly language, you don't really have loops - you have labels and conditional-branch instructions. So the loop is just a part of the overall sequence of instructions with a label and a branch somewhere:

            instruction
    label1: instruction
            instruction
            instruction
            instruction
            jump to label1  some condition
    

    and a switch instruction is branching/jumping ahead somewhat:

            evaluate expression into register r
            compare r with first case value
            branch to first case label if equal
            compare r with second case value
            branch to second case label if equal
            etc....
    first_case_label: 
            instruction
            instruction
    second_case_label: 
            instruction
            instruction
            etc...
    

    In assembly it's easily conceivable how to combine these two control structures, and when you think of it that way, their combination in C doesn't seem so weird anymore.

提交回复
热议问题