Why is continue inside a loop a bad idea?

ぃ、小莉子 提交于 2019-11-30 08:31:46

问题


Douglas Crockfod says that it is usually better to refactor the continue inside the loop.

Why is continue considered bad within a loop?


回答1:


The use of continue would mean that you have insufficient conditions written in your while.

You should instead use if inside your while loop, or add the condition into the while loop.




回答2:


Using goto, break, continue, throw, or return inside the loop body can all have the un-desired effect as well. Here's another example where the loop control and the loop body are tightly interwoven. Does it write 1, 2, and 3 as before? Are you sure?

int value = 1;
    for (;;++value)
    {
        cout << value << endl;
        if (value != 4)
            continue;
        else
            break;
    }

You might be thinking that advising you not to use return statements inside loop bodies is over zealous. Do I really mean that? Yes I do. Functions that return something should do so via a single return statement at the very end of the function. Here are some practical reasons why:

Link

Disclaimer: Not my material, I have referenced back to the source




回答3:


The effect of continue is somehow comparable to a goto to the begin of the loop. It therefore makes your code more difficult to understand - like gotos.



来源:https://stackoverflow.com/questions/4913981/why-is-continue-inside-a-loop-a-bad-idea

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