Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixed 'switch' and 'while' in C

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?

like image 658
frogatto Avatar asked Aug 31 '14 13:08

frogatto


People also ask

Can we use switch case inside while loop in C?

Yes a switch statement can be used inside a loop.

Is while () valid in C?

The code while(condition); is perfectly valid code, though its uses are few.

Can switch take two arguments in C?

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.


1 Answers

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.

like image 165
midor Avatar answered Oct 02 '22 10:10

midor