混合'开关'和'而'用C [英] Mixed 'switch' and 'while' in C

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

问题描述

我最近读此页面了解奇怪Ç段codeS。他们中的大多数是可以理解的。但我不明白这一个:

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:
}

任何人都可以请帮我出这是code的背后是什么逻辑?它是如何工作的?

Can anyone please help me out what logic is behind of this code? And how does it work?

推荐答案

本达夫设备注释应该解释背景不够好,所以我会尽力解释这种非常情况下:

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语句下面的code也是执行。控制然后到达而循环的结尾,所以跳跃到再次开始检查条件仍然是真实的。如果是,所有的循环中的语句被执行,并且重复循环,直到条件为假。初始开关通常可以确保将c将是4的倍数时的while循环的第一次运行。

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.

编辑:达夫的维基百科设备。添加链接,以更明显了我的意思以达夫设备评论。请考虑upvoting 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天全站免登陆