在 C 中混合“开关"和“同时" [英] Mixed 'switch' and 'while' in C

查看:22
本文介绍了在 C 中混合“开关"和“同时"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近阅读了这个页面,了解奇怪的 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?

推荐答案

duff 的设备注释应该已经很好地解释了背景,所以我会尽量解释这个案例:

The duff's device comment should explain the background well enough, so I ll try to explain this very case:

switch 检查 c 的最后 2 位,并跳转到 while 循环内的相应 case 语句.case 语句下面的代码也被执行.然后控制到达 while 循环的结尾,因此它再次跳到开头以检查条件是否仍然为真.如果是,则执行循环内的所有语句,并重复循环直到条件为假.初始 switch 通常确保在 while 循环第一次运行时 c 将是 4 的倍数.

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.

维基百科上的 duff 设备.添加链接以使我对达夫的设备评论"的含义更加明显.如果您对这个答案点赞,请考虑为 interjay 的评论点赞.

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.

这篇关于在 C 中混合“开关"和“同时"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆