C中的混合'switch'和'while' [英] Mixed 'switch' and 'while' in C

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

问题描述

我最近阅读了此页面关于奇怪的 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:

开关检查 c 的最后 2 位,并跳转到 while 循环内的相应 case 语句.case 语句下面的代码也被执行.控制然后到达while循环的结尾,所以它再次跳到开头以检查条件是否仍然为真.如果是,则执行循环内的所有语句,并重复循环,直到条件为假.初始开关通常确保当 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中的混合'switch'和'while'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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