duffs-device

Mixed 'switch' and 'while' in C

烈酒焚心 提交于 2019-12-01 16:30:01
问题 I've recently read this page about strange C snippet codes. Most of them was understandable. But I can't understand this one: switch(c & 3) while((c -= 4) >= 0){ foo(); case 3: foo(); case 2: foo(); case 1: foo(); case 0: } Can anyone please help me out what logic is behind of this code? And how does it work? 回答1: The duff's device comment should explain the background well enough, so I ll try to explain this very case: The switch checks the last 2 bits of c, and jumps to the respective case

Switch case weird scoping

情到浓时终转凉″ 提交于 2019-11-27 12:29:06
Reviewing some 3rd party C code I came across something like: switch (state) { case 0: if (c=='A') { // open brace // code... break; // brace not closed! case 1: // code... break; } // close brace! case 2: // code... break; } Which in the code I was reviewing appeared to be just a typo but I was surprised that it compiled with out error. Why is this valid C? What is the effect on the execution of this code compared to closing the brace at the expected place? Is there any case where this could be of use? Edit: In the example I looked at all breaks were present (as above) - but answer could also

Switch case weird scoping

喜欢而已 提交于 2019-11-27 04:00:13
问题 Reviewing some 3rd party C code I came across something like: switch (state) { case 0: if (c=='A') { // open brace // code... break; // brace not closed! case 1: // code... break; } // close brace! case 2: // code... break; } Which in the code I was reviewing appeared to be just a typo but I was surprised that it compiled with out error. Why is this valid C? What is the effect on the execution of this code compared to closing the brace at the expected place? Is there any case where this could

How does Duff's device work?

妖精的绣舞 提交于 2019-11-25 22:48:25
问题 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 don\'t get it how the Duff\'s device works. What would a more detailed explanation be? 回答1: There are some good explanations elsewhere, but let me give it a try. (This is a lot easier on a whiteboard!) Here's the Wikipedia example with some notations. Let's say you're copying 20 bytes. The flow control of the program for the