测试循环在顶部还是底部?(while vs. do while) [英] Test loops at the top or bottom? (while vs. do while)

查看:33
本文介绍了测试循环在顶部还是底部?(while vs. do while)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在大学(80 年代中期)学习 CS 时,不断重复的想法之一是始终编写在顶部(while ...)而不是底部(do ... while)进行测试的循环) 的循环.这些观点经常得到参考研究的支持,这些研究表明在顶部测试的循环在统计上比在底部测试的循环更可能是正确的.

When I was taking CS in college (mid 80's), one of the ideas that was constantly repeated was to always write loops which test at the top (while...) rather than at the bottom (do ... while) of the loop. These notions were often backed up with references to studies which showed that loops which tested at the top were statistically much more likely to be correct than their bottom-testing counterparts.

因此,我几乎总是编写在顶部进行测试的循环.如果它在代码中引入了额外的复杂性,我不会这样做,但这种情况似乎很少见.我注意到一些程序员倾向于几乎只编写在底部进行测试的循环.当我看到如下结构时:

As a result, I almost always write loops which test at the top. I don't do it if it introduces extra complexity in the code, but that case seems rare. I notice that some programmers tend to almost exclusively write loops that test at the bottom. When I see constructs like:

if (condition)
{
    do
    {
       ...
    } while (same condition);
}

或相反(while 中的if),这让我想知道他们是否真的是这样写的,或者他们是否添加了 if 当他们意识到循环没有处理空情况时的语句.

or the inverse (if inside the while), it makes me wonder if they actually wrote it that way or if they added the if statement when they realized the loop didn't handle the null case.

我已经用谷歌搜索了一些,但没有找到关于这个主题的任何文献.你们(和女孩)如何编写循环?

I've done some googling, but haven't been able to find any literature on this subject. How do you guys (and gals) write your loops?

推荐答案

我总是遵循这样的规则,如果它应该运行零次或多次,则在开始时进行测试,如果它必须运行一次或更多,最后测试.我没有看到使用您在示例中列出的代码的任何合乎逻辑的理由.它只会增加复杂性.

I always follow the rule that if it should run zero or more times, test at the beginning, if it must run once or more, test at the end. I do not see any logical reason to use the code you listed in your example. It only adds complexity.

这篇关于测试循环在顶部还是底部?(while vs. do while)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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