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?
Yes a switch statement can be used inside a loop.
The code while(condition); is perfectly valid code, though its uses are few.
Yes, this is valid, because in this case, the , is a comma operator. The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.
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-statement inside the while loop. The code below the case statement is also executed. Control then reaches the end of the while loop, so it jumps to the beginning again to check if the condition is still true. If it is, all the statements inside the loop are executed, and the loop is repeated until the condition is false. The initial switch usually ensures that c will be a multiple of 4 when the while loop runs for the first time.
Edit: duff's device on Wikipedia. Adding link to make more obvious what I meant with "the duff's device comment". Please consider upvoting interjay's comment should you upvote this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With