Mixed 'switch' and 'while' in C

后端 未结 1 509
再見小時候
再見小時候 2021-01-17 23:55

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 -=         


        
相关标签:
1条回答
  • 2021-01-18 00:42

    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.

    0 讨论(0)
提交回复
热议问题