问题
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 return
ing from the middle of a function.
来源:https://stackoverflow.com/questions/13226416/for-loop-syntax-with-if-statements-inside