for loop syntax with if statements inside

爱⌒轻易说出口 提交于 2019-12-24 00:06:15

问题


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.


回答1:


'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.




回答2:


Some people don't like continue because it is effectively a goto. For example, consider:

for (int i = 0; i < hi; i++) {
    ....
    do_this_for_each_full_iteration();
}

If the .... contains any continue statements, the do_this_after_each_full_iteration() will be bypassed.

These tend to be the same people who dislike returning from the middle of a function.



来源:https://stackoverflow.com/questions/13226416/for-loop-syntax-with-if-statements-inside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!