How can Duff's device code be compiled?

前端 未结 5 1506
既然无缘
既然无缘 2020-12-10 17:21

I understood why Duff\'s device is faster than normal loop code which can be unrolled but is not optimized. But I can\'t understand how the code can be compiled yet.
I g

5条回答
  •  爱一瞬间的悲伤
    2020-12-10 17:40

    A simple explanation of why Duff's Device compiles is that the syntax of the switch statement isn't particularly specific about the form that the switch statement block might need to take. There are a few restrictions, and a couple of things permitted in the controlled statement that aren't permitted outside a switch (the case and default labels). But other than that, the controlled statement is just any other statement, with the likelihood that there are labels for the switch to target.

    Here's the syntax from C99:

    switch ( expression ) statement
    

    Beyond the syntax, the standard imposes a few constraints:

    • the controlling expression must have an integer type
    • there are restrictions about where VLAs can occur in the switch statement
    • case label expressions must be integer constant expressions
    • there cannot be duplicate case label expressions or default labels

    Other than that, any construct permitted in a statement block should be permitted in the controlled statement (with the addition that case and default labels are OK). Remember that case and default are just labels that the switch jumps to based on the controlling expression and the case label expressions. As Potatoswatter says, switch is just a computed goto. So just like goto can jump into the middle of a loop, so can switch.

    Also, I think that the cases where you might see a benefit from Duff's Device are pretty rare today (I think they were rare even in the 1980's). Don't forget that Tom Duff himself said the following in his description:

    • "Disgusting, no?"
    • "I feel a combination of pride and revulsion at this discovery."

    Even more than when it was initially described, Duff's Device should be considered more of a curiosity than a tool to use.

提交回复
热议问题