Just yesterday, I first met the curious Duff device . I read about it, and I don’t think it’s hard to understand. I am interested in the strange syntax (from Wikipedia):
register short *to, *from; register int count; { register int n = (count + 7) / 8; switch(count % 8) { case 0: do { *to = *from++; case 7: *to = *from++; case 6: *to = *from++; case 5: *to = *from++; case 4: *to = *from++; case 3: *to = *from++; case 2: *to = *from++; case 1: *to = *from++; } while(--n > 0); } }
I read the standard definition of the C ++ operator (let me know if this is deprecated, I am not familiar with Open-Std.org). As I understand it, case statements are simply simplified branch instructions for use by the switch statement.
The switch itself completely ignores the nested do-while, and the loop ignores case statements. Since the switch jumps inside the loop, the loop executes. The switch should close the remainder (dividing by 8), and the loop processes the part that is evenly divided. All this makes sense.
Then my question is why the syntax is awkward? It occurs to me that a cycle can be written so that all the statements of the case are contained inside, right? I don’t see anything in the standard that prohibits this behavior, and it compiles correctly in accordance with GCC 4.7, so what is considered legal next?
register short *to, *from; register int count; { register int n = (count + 7) / 8; switch (count <= 0 ? 8 : count % 8) { do { case 0: *to = *from++; case 7: *to = *from++; case 6: *to = *from++; case 5: *to = *from++; case 4: *to = *from++; case 3: *to = *from++; case 2: *to = *from++; case 1: *to = *from++; default: ;
For me, this makes the code much clearer. Thanks for any feedback .;)
Edit: As indicated below, the source code was written for C and had an implicit int for count and n variables. Since I marked it in C ++, I changed this.
Edit 2: The revised example code has been changed to account for invalid account values.
c ++ switch-statement
monkey_05_06
source share