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 guess it's a trick about the switch syntax. But not anymore.
How can do while sentence exist in switch sentence? Very weird.
Is there anyone who can explain this?
Edit: Another question. Why did duff use 8? It could be 16, 65536 or whatever. Because of code size? Is there another reason? For example, cache or pipelining benefits.
A simple explanation of why Duff's Device compiles is that the syntax of the
switchstatement isn't particularly specific about the form that theswitchstatement 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 aswitch(thecaseanddefaultlabels). But other than that, the controlled statement is just any other statement, with the likelihood that there are labels for theswitchto target.Here's the syntax from C99:
Beyond the syntax, the standard imposes a few constraints:
caselabel expressions must be integer constant expressionscaselabel expressions ordefaultlabelsOther than that, any construct permitted in a statement block should be permitted in the controlled statement (with the addition that
caseanddefaultlabels are OK). Remember thatcaseanddefaultare just labels that the switch jumps to based on the controlling expression and thecaselabel expressions. As Potatoswatter says,switchis just a computedgoto. So just likegotocan jump into the middle of a loop, so canswitch.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:
Even more than when it was initially described, Duff's Device should be considered more of a curiosity than a tool to use.