for循环语法与if语句 [英] for loop syntax with if statements inside

查看:173
本文介绍了for循环语法与if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用if语句编写for循环的一般共识是:

  for(int i = 0; i < hi; i ++){
if(一些无效条件){
continue;
}

if(另一个无效条件){
continue;
}

//通过所有无效条件后在这里执行
}

而不是

  for(int i = 0; i< hi; i ++){ 
if(有效条件1&&&&>有效条件2& ...){
// do stuff
}
pre>

在我看来,编写它的第一种方法是更干净,更方便调试,虽然它需要更多的线。我的主要问题是,如果有第二种方式写的任何优势。即使只有一个if语句,它似乎写的第一种方式将更好地使它更容易维护/调试在未来。

解决方案

CONTINUE在循环中是非常罕见的。在大多数情况下,在循环中遇到无效情况自然会导致BREAK。但是,您的示例没有错误,如果这适合您的业务逻辑,它可能更合适。


What is the general consensus on writing for loops with if statements like this:

for (int i = 0; i < hi; i++) {
    if (some invalid condition) {
        continue;
    }

    if (another invalid condition) {
        continue;
    }

    //do stuff here after passing all the invalid conditions
}

as opposed to

for (int i = 0; i < hi; i++) {
    if (valid condition1 && valid condition 2 && ...) {
        //do stuff
}

It seems to me that the first way of writing it is much cleaner and more convenient for debugging, though it takes up more lines. My main question is if there's ever any advantage to writing it the second way. Even when there is just one if statement, it seems like writing it the first way would be better to make it easier to maintain/debug in the future.

解决方案

'CONTINUE' in loops is pretty rare. In most cases encountering invalid situation inside a loop will naturally result in 'BREAK' instead. However there is nothing wrong with your example and it may indeed be more suitable if this fits your business logic.

这篇关于for循环语法与if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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