8

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

Why is continue considered bad within a loop?

Myles Gray
  • 8,055
  • 7
  • 46
  • 69
unj2
  • 47,759
  • 80
  • 235
  • 362
  • 1
    See also [Continue in nested while loops](http://stackoverflow.com/questions/1133408/continue-in-nested-while-loops). There's very little that's specific to C#, and many of the answers provided there are excellent. – Cody Gray Feb 06 '11 at 14:58

3 Answers3

7

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.

mauris
  • 39,624
  • 14
  • 92
  • 128
  • 2
    +1 *This* is the (only sane) reason to avoid `continue` (*in most cases*, not all the time). –  Feb 06 '11 at 14:58
  • -1 Just saying "because `if` is better" does not answer the question at all. – twiz Sep 20 '14 at 13:51
4

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

Myles Gray
  • 8,055
  • 7
  • 46
  • 69
1

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.

Christoph
  • 1,847
  • 2
  • 26
  • 41
  • 7
    -1 `if (...) { ... } ...` is somewhat comparable to a `goto` to the end of the block. Seriously, blindly disregarding anything remotely resembling a specialized case of `goto` is as harmful as eregious abuse of unfitting control structures (e.g. using `goto` when a higher-level control structure for the problem at hand exists). –  Feb 06 '11 at 14:57
  • @delnan There's quite a difference between conditional branching downwards and non-conditional branching upwards. If you ever read complex assembly code, you will know why. That being said, using `goto` can actually be acceptable, but only for non-conditional branching downwards. Unlike `continue`, which is broken by design, as it always branches upwards. The presence of `continue` is always an indication of a poorly written loop, every loop using it can be rewritten in a better way. – Lundin Mar 03 '16 at 12:35